The Open Framework for Building Agents
fix(eve): publish the MCP invocation contract to clients (#2988)
Colton Padden6e3592310986
diff --git a/.changeset/mcp-invocation-contract-instructions.md b/.changeset/mcp-invocation-contract-instructions.mdnew file mode 100644index 000000000..14aed6fda--- /dev/null+++ b/.changeset/mcp-invocation-contract-instructions.md@@ -0,0 +1,5 @@+---+"eve": patch+---++The MCP channel now returns server `instructions` from `initialize` and `server/discover` that summarize the durable invocation protocol, and its tool descriptions state polling cadence, complete-batch input answers, cooperative cancellation, and that `agent_start` is not idempotent. Hosted MCP clients no longer have to infer the lifecycle from the tool schemas.diff --git a/docs/channels/mcp.mdx b/docs/channels/mcp.mdxindex d7f93a294..e12c9c909 100644--- a/docs/channels/mcp.mdx+++ b/docs/channels/mcp.mdx@@ -67,6 +67,8 @@ The authorization server identified by `issuer` must issue tokens accepted by th`oauthResource()` does not issue tokens or run an authorization server. It decorates an ordinary inbound `AuthFn` with OAuth protected-resource metadata so `mcpChannel()` can publish discovery and add `resource_metadata` to Bearer challenges. Client registration, consent, token issuance, and authorization-server metadata remain the identity provider's responsibility.+Most hosted MCP clients (Claude, ChatGPT, Grok, and similar) register themselves with the authorization server through Dynamic Client Registration ([RFC 7591](https://www.rfc-editor.org/rfc/rfc7591)) the first time a user connects. Choose an issuer that supports it, or pre-register each client with the issuer before the demo. If registration fails, the client stops before it ever reaches eve.+### Verify the bearer token yourselfUse a custom `AuthFn` when token verification needs application-specific logic:@@ -144,7 +146,7 @@ export default mcpChannel({});```-This allows anyone to invoke the agent. Every caller shares the anonymous principal, so invocation IDs become bearer capabilities until workflow retention expires. Use public access only when anonymous invocation is intentional.+This allows anyone to invoke the agent. Every caller shares the anonymous principal, so invocation IDs become bearer capabilities until workflow retention expires: anyone holding an ID can read, answer, or cancel that invocation. Use public access only when anonymous invocation is intentional. For a public demo, prefer [Interactive OAuth](#interactive-oauth) so each caller owns their own invocations.## HTTP security@@ -171,6 +173,10 @@ MCP clients receive four tools:| `agent_update` | `{ invocationId, responses }` | Answer the complete pending human-input batch. || `agent_cancel` | `{ invocationId }` | Request cooperative cancellation of non-terminal work. |+The server also returns `instructions` from `initialize` and `server/discover` that summarize this+protocol for the connecting model, so a hosted client does not have to infer it from the tool+schemas alone.+`agent_start` creates one task-mode eve session and returns after durable acceptance withoutwaiting for the session continuation hook to become readable. Keep its `invocationId`, then call`agent_get` until the invocation reaches a terminal state. While the status is `working`, wait at@@ -179,16 +185,28 @@ least `pollAfterMs` before polling again.The invocation response is discriminated by `status`:- `working`: work is active; continue polling according to `pollAfterMs`.-- `input_required`: present `inputRequests`, then send the complete answer batch through `agent_update`. A successful update returns fresh `working` state.+- `input_required`: present `inputRequests`, then send the complete answer batch through `agent_update`. A successful update returns the current invocation state.- `authorization_required`: present the returned sign-in URL, user code, or instructions. The connection callback resumes the invocation automatically; continue polling.- `completed`: consume the optional `result`.- `failed`: inspect the structured `error`.- `cancelled`: cancellation reached a terminal state.+A tool result with `isError: true` means the call itself was rejected (unknown invocation, no input+pending, incomplete response batch, invalid output schema). A `failed` status means the call+succeeded and the task itself failed. Handle them differently: correct the call in the first case,+report the task failure in the second.+Cancellation is cooperative, so call `agent_get` after `agent_cancel` until the state becomes terminal.Optional output schemas are limited to 64 KiB, 32 levels, and 2,048 nodes. External `$ref` values are rejected.+### Durability guarantees++- Once `agent_start` returns, the work is durable. A dropped HTTP connection, a client restart, or a closed MCP session does not cancel it. Only `agent_cancel` stops work.+- `agent_start` is not idempotent. If its response is lost, the client has no `invocationId` to check, and a second call starts a second task. Ask the user before starting again rather than retrying blindly.+- `agent_update` answers one pending batch. Re-sending the same answers after eve has accepted them returns the current invocation state; sending different answers for an already-answered batch is a conflict.+- `agent_cancel` is cooperative and can race with completion. Poll `agent_get` until the status is terminal (`cancelled`, `completed`, or `failed`), not specifically `cancelled`.+## Invocation ownershipEvery MCP operation reruns the configured auth policy. With authenticated policies, an invocation belongs to the principal that started it; knowing its ID is not sufficient. Bearer tokens are not stored with the invocation or forwarded to the agent's tools.diff --git a/packages/eve/scripts/vendor-compiled/@modelcontextprotocol/server.mjs b/packages/eve/scripts/vendor-compiled/@modelcontextprotocol/server.mjsindex ecaea6b9f..c02399f5e 100644--- a/packages/eve/scripts/vendor-compiled/@modelcontextprotocol/server.mjs+++ b/packages/eve/scripts/vendor-compiled/@modelcontextprotocol/server.mjs@@ -56,6 +56,7 @@ export declare class Server {export declare class McpServer {constructor(info: { readonly name: string; readonly version: string }, options?: {readonly capabilities?: Readonly<Record<string, unknown>>;+ readonly instructions?: string;});registerTool<TInput = unknown, TOutput = TInput>(name: string,diff --git a/packages/eve/src/internal/mcp/streamable-http-server.ts b/packages/eve/src/internal/mcp/streamable-http-server.tsindex ed043c8ed..9a72c07a6 100644--- a/packages/eve/src/internal/mcp/streamable-http-server.ts+++ b/packages/eve/src/internal/mcp/streamable-http-server.ts@@ -84,6 +84,8 @@ export function defineMcpTool<export interface McpStreamableHttpServerOptions {readonly name: string;readonly version: string;+ /** Server-level usage guidance returned from `initialize` and `server/discover`. */+ readonly instructions?: string;readonly tools: readonly McpServerTool[];authenticate(request: Request): Promise<SessionAuthContext | null | Response>;}@@ -298,14 +300,15 @@ function readJsonRpcRequestId(body: unknown): string | number | null {}function createServer(- options: Pick<McpStreamableHttpServerOptions, "name" | "version">,+ options: Pick<McpStreamableHttpServerOptions, "instructions" | "name" | "version">,tools: ReadonlyMap<string, McpServerTool>,auth: SessionAuthContext | null,): McpServer {- const server = new McpServer(- { name: options.name, version: options.version },- { capabilities: { tools: { listChanged: false } } },- );+ const serverOptions: { capabilities: Record<string, unknown>; instructions?: string } = {+ capabilities: { tools: { listChanged: false } },+ };+ if (options.instructions !== undefined) serverOptions.instructions = options.instructions;+ const server = new McpServer({ name: options.name, version: options.version }, serverOptions);for (const tool of tools.values()) tool.register(server, auth);diff --git a/packages/eve/src/public/channels/mcp.test.ts b/packages/eve/src/public/channels/mcp.test.tsindex 25fbad3c1..96f07d960 100644--- a/packages/eve/src/public/channels/mcp.test.ts+++ b/packages/eve/src/public/channels/mcp.test.ts@@ -7,7 +7,10 @@ import {attachRouteChannelName,attachRouteSessionCreator,} from "#internal/nitro/routes/channel-route-context.js";-import { MCP_LEGACY_PROTOCOL_VERSION } from "#internal/mcp/streamable-http-server.js";+import {+ MCP_LEGACY_PROTOCOL_VERSION,+ MCP_PROTOCOL_VERSION,+} from "#internal/mcp/streamable-http-server.js";import { ForbiddenError, none, oauthResource, withAuthChallenges } from "#public/channels/auth.js";import { mcpChannel } from "#public/channels/mcp.js";@@ -49,9 +52,38 @@ describe("mcpChannel", () => {routeArgs(),);await expect(jsonRpcResponse(initialize)).resolves.toMatchObject({- result: { serverInfo: { name: "compiled-agent" } },+ result: {+ instructions: expect.stringContaining("pollAfterMs"),+ serverInfo: { name: "compiled-agent" },+ },});+ const discovered = await postRoute.handler(+ mcpRequest(+ {+ id: "discover",+ jsonrpc: "2.0",+ method: "server/discover",+ params: {+ _meta: {+ "io.modelcontextprotocol/clientCapabilities": {},+ "io.modelcontextprotocol/clientInfo": { name: "test-client", version: "0.0.0" },+ "io.modelcontextprotocol/protocolVersion": MCP_PROTOCOL_VERSION,+ },+ },+ },+ { "mcp-method": "server/discover", "mcp-protocol-version": MCP_PROTOCOL_VERSION },+ ),+ routeArgs(),+ );+ const discovery = (await jsonRpcResponse(discovered)) as {+ result: { instructions: string };+ };+ expect(discovery.result.instructions).toContain("agent_start is not idempotent");+ expect(discovery.result.instructions).toContain("ask the user before starting again");+ expect(discovery.result.instructions).toContain("agent_cancel");+ expect(discovery.result.instructions.length).toBeLessThan(800);+const tools = await postRoute.handler(mcpRequest({ id: 2, jsonrpc: "2.0", method: "tools/list" }),routeArgs(),@@ -80,13 +112,18 @@ describe("mcpChannel", () => {description: expect.stringContaining("Investigates tasks."),outputSchema: { type: "object" },});+ expect(body.result.tools[0]?.description).toContain("Not idempotent");expect(body.result.tools[1]).toMatchObject({annotations: {idempotentHint: true,openWorldHint: false,readOnlyHint: true,},+ description: expect.stringContaining("pollAfterMs"),});+ expect(body.result.tools[2]?.description).toContain("partial batches are rejected");+ expect(body.result.tools[3]?.description).toContain("until status is terminal");+ expect(body.result.tools[3]?.description).not.toContain("until status is cancelled");expect(body.result.tools[2]).toMatchObject({annotations: {idempotentHint: false,diff --git a/packages/eve/src/public/channels/mcp.ts b/packages/eve/src/public/channels/mcp.tsindex 86a06080f..5df260de0 100644--- a/packages/eve/src/public/channels/mcp.ts+++ b/packages/eve/src/public/channels/mcp.ts@@ -366,6 +366,7 @@ async function handleMcpRequest(});return await createMcpStreamableHttpServer({authenticate: async () => auth,+ instructions: MCP_SERVER_INSTRUCTIONS,name: agentInfo.agent.name,tools: createInvocationTools(execution,@@ -376,6 +377,22 @@ async function handleMcpRequest(})(request);}+/**+ * Hosted MCP clients receive this once per connection (legacy `initialize`)+ * or per discovery (`server/discover`). Keep it short: clients truncate or+ * drop long instructions, and the details live in each tool description.+ */+const MCP_SERVER_INSTRUCTIONS = [+ "Each invocation is one durable agent task.",+ "Call agent_start once per task and keep the returned invocationId.",+ "Poll agent_get, waiting at least pollAfterMs between calls, until status is completed, failed, or cancelled.",+ "If status is input_required, answer every entry in inputRequests in one agent_update call; repeating accepted answers is safe.",+ "If status is authorization_required, show the user the authorization url or instructions and keep polling.",+ "isError on a tool result means your call was rejected; a failed status means the task failed.",+ "agent_start is not idempotent and a lost response leaves no invocationId, so ask the user before starting again.",+ "Work continues after your connection drops; agent_cancel stops it, then poll until any terminal status.",+].join(" ");+function createInvocationTools(execution: WorkflowAgentInvocationExecution,agentDescription: string | undefined,@@ -384,7 +401,10 @@ function createInvocationTools(const publicHandleDescription = publicAccess? " On this public channel, the invocation ID is a bearer capability until workflow retention expires.": "";- const startDescription = `Starts durable work and returns an invocation handle immediately.${publicHandleDescription}`;+ const startDescription =+ "Starts durable work and returns an invocation handle immediately. " ++ "Call once per task; keep invocationId and poll agent_get. Not idempotent: if the response is lost, " ++ `ask the user before starting again rather than retrying.${publicHandleDescription}`;const tools: McpServerTool[] = [defineMcpTool({definition: {@@ -422,7 +442,10 @@ function createInvocationTools(openWorldHint: false,readOnlyHint: true,},- description: `Reads complete durable invocation state.${publicHandleDescription}`,+ description:+ "Reads complete durable invocation state. Wait at least pollAfterMs between calls. " ++ "Terminal statuses are completed, failed, and cancelled. input_required needs agent_update; " ++ `authorization_required needs the user to follow the returned authorization.${publicHandleDescription}`,inputSchema: z.strictObject({ invocationId: z.string().min(1) }),name: "agent_get",outputSchema: AGENT_INVOCATION_OUTPUT_SCHEMA,@@ -446,7 +469,10 @@ function createInvocationTools(openWorldHint: true,readOnlyHint: false,},- description: "Answers a pending input request on a durable invocation.",+ description:+ "Answers the pending input batch on an input_required invocation. Include one response per " ++ "entry in inputRequests, each keyed by its requestId, in a single call; partial batches are rejected. " ++ "Returns the current invocation state; repeating the same accepted answers is safe.",inputSchema: z.strictObject({invocationId: z.string().min(1),responses: z.array(inputResponseSchema).min(1),@@ -475,7 +501,9 @@ function createInvocationTools(readOnlyHint: false,},description:- "Requests cancellation of a durable invocation. Read it again to observe acknowledgement.",+ "Requests cooperative cancellation of a non-terminal invocation. Cancellation is asynchronous and " ++ "can race with completion: poll agent_get until status is terminal (cancelled, completed, or failed). " ++ "Safe to call repeatedly.",inputSchema: z.strictObject({ invocationId: z.string().min(1) }),name: "agent_cancel",outputSchema: AGENT_INVOCATION_OUTPUT_SCHEMA,