The Open Framework for Building Agents
feat(eve): let mcpChannel publish the agent's tools with tools: true (#4124)
Ruia2c2687a4551
diff --git a/.changeset/mcp-channel-tools.md b/.changeset/mcp-channel-tools.mdnew file mode 100644index 000000000..3cae0e97a--- /dev/null+++ b/.changeset/mcp-channel-tools.md@@ -0,0 +1,5 @@+---+"eve": patch+---++`mcpChannel` can now publish the agent's own tools next to the `agent_*` tools. Set `tools: true` to list every tool the agent can run outside a conversation, with its JSON schemas, and run each `tools/call` as the route-authenticated caller. Set `agent: false` to stop serving the `agent_*` tools. Both default to what the channel served before, so existing channels do not change.diff --git a/docs/channels/mcp.mdx b/docs/channels/mcp.mdxindex f08b82587..de50aa268 100644--- a/docs/channels/mcp.mdx+++ b/docs/channels/mcp.mdx@@ -3,7 +3,7 @@ title: "MCP Channel"description: "Publish an eve agent as an MCP server with auth support."----The MCP channel lets clients such as Claude Code delegate durable work to an eve agent through four tools: `agent_start`, `agent_get`, `agent_update`, and `agent_cancel`.+The MCP channel lets clients such as Claude Code delegate durable work to an eve agent through four tools: `agent_start`, `agent_get`, `agent_update`, and `agent_cancel`. It can also publish the agent's own tools, so a client calls them directly; see [Publish the agent's tools](#publish-the-agents-tools).Use an [MCP connection](../connections/mcp) instead when your eve agent needs to call someone else's MCP server.@@ -211,6 +211,44 @@ Requests are bounded: the whole MCP request body is limited to 1 MiB, `message`- `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`.+## Publish the agent's tools++By default the channel serves only the `agent_*` tools. Set `tools: true` to also publish every tool the agent can run outside a conversation, and `agent: false` to stop serving the `agent_*` tools:++```ts title="agent/channels/mcp.ts"+import { localDev } from "eve/channels/auth";+import { mcpChannel } from "eve/channels/mcp";++export default mcpChannel({+ auth: localDev(),+ tools: true,+});+```++`tools/list` returns the `agent_*` tools first, then the agent's tools in name order with their input and output JSON schemas. Framework tools, workflow and provider tools, tools without `execute`, and tools added by dynamic resolvers or subagents are not published. While `agent` is on, an agent tool named `agent_start`, `agent_get`, `agent_update`, or `agent_cancel` is not published, and eve logs a warning. With `agent: false`, the channel sends no `agent_*` instructions. Turning off both `agent` and `tools` throws.++Each `tools/call` checks the arguments against the tool's input schema, then runs the tool as the route-authenticated caller, with no model, turn, or workflow run. Every caller the channel's `auth` admits can call these tools, outside the agent's instructions, so review what becomes callable before you turn this on. Each call gets its own session:++- Authored state starts from its initial value, and updates are not kept.+- A sandbox the tool opens is deleted when the call ends.+- Calls may run in parallel, and a call retried after a lost response runs again.++A tool that cannot finish over MCP returns an error result with `isError: true` and a `structuredContent.error.code`:++| Code | When |+| ------------------------ | ------------------------------------------------------------------------------------------------ |+| `invalid_input` | The tool rejected its input. |+| `denied` | The tool's approval policy denied the call. |+| `approval_required` | The approval policy asks a person. The tool did not run; call it from a conversation instead. |+| `authorization_required` | The tool needs a sign-in to a connection first. Sign in from a conversation, then call it again. |+| `internal` | The tool failed. The message carries an error id that matches the server logs. |++### Trace context++MCP clients send W3C trace context in each request's `params._meta`, not in HTTP headers. When a request carries a valid `_meta.traceparent`, that span becomes the parent of everything the request runs, including a published tool's `execute_tool` span. It takes precedence over any parent your platform extracted from the HTTP request's headers. A missing, malformed, or all-zero `traceparent` leaves that parent in place. `_meta.tracestate` is kept only alongside a valid `_meta.traceparent` and only up to 512 characters; a longer value is dropped.++`_meta.baggage` is never read. A caller cannot choose the trace audience, session lineage, or content capture: those come from the channel and your `tracePolicy`, as they do for conversations. The `execute_tool` span records the call's arguments and result only when that content decision allows it, and never records exception text.+## 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/src/internal/mcp/published-tools.ts b/packages/eve/src/internal/mcp/published-tools.tsnew file mode 100644index 000000000..ec939afa8--- /dev/null+++ b/packages/eve/src/internal/mcp/published-tools.ts@@ -0,0 +1,97 @@+import { fromJsonSchema } from "#compiled/@modelcontextprotocol/server/index.js";++import type { AgentToolDescription } from "#channel/agent-description.js";+import type { InvokeToolFn, InvokeToolResult } from "#channel/invoke-tool.js";+import { createLogger } from "#internal/logging.js";+import {+ defineMcpTool,+ McpToolOperationError,+ type McpCallToolResult,+ type McpServerTool,+} from "#internal/mcp/streamable-http-server.js";+import { isJsonObjectValue, type JsonValue } from "#shared/json.js";++const log = createLogger("mcp.tools");+const warnedReserved = new Set<string>();++/**+ * The agent's invocable tools as MCP tools. Each `tools/call` runs the tool+ * through `invokeTool` as the route-authenticated caller. Tools named like+ * one in `reserved` are skipped, since the channel serves that name itself.+ */+export function createPublishedTools(input: {+ readonly invokeTool: InvokeToolFn;+ readonly reserved: ReadonlySet<string>;+ readonly tools: readonly AgentToolDescription[];+}): McpServerTool[] {+ return input.tools+ .filter((tool) => {+ if (!input.reserved.has(tool.name)) return true;+ if (!warnedReserved.has(tool.name)) {+ warnedReserved.add(tool.name);+ log.warn(+ `mcpChannel does not publish the tool "${tool.name}": the channel serves that name.`,+ );+ }+ return false;+ })+ .map((tool) =>+ defineMcpTool({+ definition: {+ description: tool.description,+ inputSchema: fromJsonSchema(tool.inputSchema),+ name: tool.name,+ outputSchema:+ tool.outputSchema === undefined ? undefined : fromJsonSchema(tool.outputSchema),+ },+ async call(value, { auth, signal }) {+ if (auth === null) {+ throw new McpToolOperationError("denied", "The channel authenticated no caller.");+ }+ const result = await input.invokeTool(tool.name, value, { auth, signal });+ return toCallToolResult(tool.name, result, tool.outputSchema !== undefined);+ },+ }),+ );+}++function toCallToolResult(+ name: string,+ result: InvokeToolResult,+ hasOutputSchema: boolean,+): McpCallToolResult<JsonValue> {+ switch (result.status) {+ case "completed": {+ const output = result.output as JsonValue;+ const text =+ result.modelOutput.type === "text"+ ? result.modelOutput.value+ : JSON.stringify(output ?? null);+ // A declared outputSchema obliges structured content of any JSON type: the+ // SDK rejects a result without it and wraps non-objects as `{ result }` on+ // 2025 connections. Without a schema, only objects are structured.+ return hasOutputSchema || isJsonObjectValue(output)+ ? { content: [{ text, type: "text" }], structuredContent: output ?? null }+ : { content: [{ text, type: "text" }] };+ }+ case "invalid-input":+ throw new McpToolOperationError("invalid_input", result.message);+ case "denied":+ throw new McpToolOperationError(+ "denied",+ result.reason ?? `The tool "${name}" was denied by its approval policy.`,+ );+ case "approval-required":+ throw new McpToolOperationError(+ "approval_required",+ `The tool "${name}" needs a person's approval, which this MCP channel cannot ask for. Call it from a conversation instead.`,+ );+ case "authorization-required":+ throw new McpToolOperationError(+ "authorization_required",+ `The tool "${name}" needs a sign-in to ${result.connections.join(", ")}, which this MCP channel cannot ask for. Sign in from a conversation, then call it again.`,+ );+ case "failed":+ throw new McpToolOperationError("internal", result.message);+ }+}diff --git a/packages/eve/src/internal/mcp/request-trace-context.ts b/packages/eve/src/internal/mcp/request-trace-context.tsnew file mode 100644index 000000000..d17fc58d7--- /dev/null+++ b/packages/eve/src/internal/mcp/request-trace-context.ts@@ -0,0 +1,57 @@+import {+ createTraceState,+ trace,+ TraceFlags,+ type Context,+ type SpanContext,+} from "#compiled/@opentelemetry/api/index.js";++import { isObject } from "#shared/guards.js";++/** W3C caps `tracestate` at 512 characters; a longer value is dropped whole. */+const MAX_TRACESTATE_LENGTH = 512;+const TRACEPARENT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;+const ZERO_TRACE_ID = "0".repeat(32);+const ZERO_SPAN_ID = "0".repeat(16);++/**+ * Adopts the W3C trace context an MCP client sends in a request's+ * `params._meta` as the parent of everything the request runs.+ *+ * Only `traceparent` and `tracestate` are read, and each is validated and+ * bounded; anything malformed leaves `parent` as it was. `baggage` is never+ * read: an MCP caller cannot choose eve's audience, session lineage, or+ * content capture by sending it. Every other value already on `parent`,+ * error-content policy included, is kept.+ */+export function withMcpRequestTraceContext(parent: Context, body: unknown): Context {+ if (!isObject(body) || Array.isArray(body) || !isObject(body.params)) return parent;+ const meta = body.params._meta;+ if (!isObject(meta)) return parent;+ const traceparent = meta.traceparent;+ if (typeof traceparent !== "string") return parent;+ const match = TRACEPARENT.exec(traceparent);+ if (match === null) return parent;+ const traceId = match[1];+ const spanId = match[2];+ const flags = match[3];+ if (traceId === undefined || spanId === undefined || flags === undefined) return parent;+ if (traceId === ZERO_TRACE_ID || spanId === ZERO_SPAN_ID) return parent;++ const tracestate = meta.tracestate;+ const traceState =+ typeof tracestate === "string" &&+ tracestate.length > 0 &&+ tracestate.length <= MAX_TRACESTATE_LENGTH+ ? createTraceState(tracestate)+ : undefined;+ const spanContext: SpanContext = {+ isRemote: true,+ spanId,+ traceFlags: Number.parseInt(flags, 16) & TraceFlags.SAMPLED,+ traceId,+ };+ if (traceState !== undefined) spanContext.traceState = traceState;+ const remote = trace.wrapSpanContext(spanContext);+ return trace.setSpan(parent, remote);+}diff --git a/packages/eve/src/internal/mcp/streamable-http-server.ts b/packages/eve/src/internal/mcp/streamable-http-server.tsindex 5722b7b74..791aabd41 100644--- a/packages/eve/src/internal/mcp/streamable-http-server.ts+++ b/packages/eve/src/internal/mcp/streamable-http-server.ts@@ -1,3 +1,4 @@+import { context as otelContext } from "#compiled/@opentelemetry/api/index.js";import {createMcpHandler,McpServer,@@ -8,6 +9,7 @@ import {import type { SessionAuthContext } from "#channel/types.js";import { createLogger, logError } from "#internal/logging.js";+import { withMcpRequestTraceContext } from "#internal/mcp/request-trace-context.js";const log = createLogger("mcp.server");@@ -26,9 +28,11 @@ interface McpToolDefinition<TInputSchema extends StandardSchemaWithJSON = Standareadonly outputSchema?: StandardSchemaWithJSON;}-export interface McpCallToolResult<- TStructured extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,-> {+/**+ * `TStructured` is any JSON value: 2026 clients accept non-object structured+ * content, and the SDK wraps it as `{ result }` for 2025 clients.+ */+export interface McpCallToolResult<TStructured = Readonly<Record<string, unknown>>> {readonly content: readonly McpContent[];readonly isError?: boolean;readonly structuredContent?: TStructured | McpToolOperationErrorEnvelope;@@ -48,7 +52,14 @@ export type McpContent =* change or re-read something; `not_found` means stop; `internal` means the* server failed and `errorId` correlates with its logs.*/-type McpToolOperationErrorCode = "invalid_input" | "not_found" | "conflict" | "internal";+type McpToolOperationErrorCode =+ | "invalid_input"+ | "not_found"+ | "conflict"+ | "denied"+ | "approval_required"+ | "authorization_required"+ | "internal";interface McpToolOperationErrorData {readonly code: McpToolOperationErrorCode;@@ -82,7 +93,7 @@ type InferSchemaOutput<TSchema> =/** Keeps a schema and its inferred handler input coupled while erasing heterogeneous storage. */export function defineMcpTool<const TInputSchema extends StandardSchemaWithJSON<unknown, unknown>,- TStructured extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,+ TStructured = Readonly<Record<string, unknown>>,>(input: {readonly definition: McpToolDefinition<TInputSchema>;call(@@ -195,7 +206,14 @@ export function createMcpStreamableHttpServer(const preflightFailure = await preflightModernRequest(request, parsedBody);if (preflightFailure !== undefined) return preflightFailure;- return await handler.fetch(request, { parsedBody });+ // The client's trace context rides in `_meta`, not headers, so it is+ // adopted here, before the SDK dispatches into a tool. A valid+ // `_meta.traceparent` replaces any parent extracted from the HTTP+ // headers; anything else keeps it. `_meta.baggage` is never read.+ return await otelContext.with(+ withMcpRequestTraceContext(otelContext.active(), parsedBody),+ () => handler.fetch(request, { parsedBody }),+ );};}@@ -382,7 +400,7 @@ function createServer(return server;}-async function callTool<TInput, TStructured extends Readonly<Record<string, unknown>>>(+async function callTool<TInput, TStructured>(call: (input: TInput,context: { readonly auth: SessionAuthContext | null; readonly signal: AbortSignal },@@ -413,9 +431,7 @@ async function callTool<TInput, TStructured extends Readonly<Record<string, unkn}}-function toolError<TStructured extends Readonly<Record<string, unknown>>>(- error: McpToolOperationErrorData,-): McpCallToolResult<TStructured> {+function toolError<TStructured>(error: McpToolOperationErrorData): McpCallToolResult<TStructured> {const text =error.errorId === undefined ? error.message : `${error.message} (errorId: ${error.errorId})`;// The SDK skips outputSchema validation when isError is set, so this shapediff --git a/packages/eve/src/public/channels/mcp.ts b/packages/eve/src/public/channels/mcp.tsindex c689c655d..deb0067e7 100644--- a/packages/eve/src/public/channels/mcp.ts+++ b/packages/eve/src/public/channels/mcp.ts@@ -16,6 +16,7 @@ import type {} from "#internal/invocation/agent-invocation.js";import { WorkflowAgentInvocationExecution } from "#internal/invocation/workflow-execution.js";import { resolveInstalledPackageInfo } from "#internal/application/package.js";+import { createPublishedTools } from "#internal/mcp/published-tools.js";import { validateMcpHttpRequest, validateMcpMetadataRequest } from "#internal/mcp/http-security.js";import {createMcpStreamableHttpServer,@@ -46,15 +47,30 @@ export interface McpChannelInput {readonly auth: AuthFn<Request> | readonly AuthFn<Request>[];/** Override the default MCP route path (`/eve/v1/mcp`). */readonly route?: string;+ /**+ * Serve the `agent_*` tools, which start and follow a durable agent task.+ * With `false`, the channel serves only the tools `tools` publishes.+ * @default true+ */+ readonly agent?: boolean;+ /**+ * Also publish the agent's invocable tools, each `tools/call` running the+ * tool as the route-authenticated caller. While `agent` is on, an agent+ * tool named like an `agent_*` tool is not published.+ * @default false+ */+ readonly tools?: boolean;}-/** Public MCP channel exposing durable agent invocation compatibility tools. */+/** Public MCP channel publishing this agent's `agent_*` tools and, optionally, its own tools. */export type McpChannel = Channel;/*** Publishes this agent as a stateless Streamable HTTP MCP server.*- * This channel owns only MCP transport and durable eve invocation. It reuses+ * This channel owns MCP transport, durable eve invocation through the+ * `agent_*` tools (unless `agent: false`), and, with `tools: true`, the+ * agent's invocable tools, each call run through `invokeTool`. It reuses* eve's inbound auth strategies and recognizes `oauthResource(...)` metadata* when OAuth discovery is needed.* The file containing this channel must be `agent/channels/mcp.ts`.@@ -63,20 +79,27 @@ export function mcpChannel(input: McpChannelInput): McpChannel {if (input?.auth === undefined) {throw new Error("mcpChannel requires auth. Use none() for explicit public access.");}+ const publish: McpPublishOptions = { agent: input.agent ?? true, tools: input.tools ?? false };+ if (!publish.agent && !publish.tools) {+ throw new Error("mcpChannel publishes nothing with agent and tools both false. Enable one.");+ }const path = input.route ?? "/eve/v1/mcp";const oauth = readOAuthResourceOptions(input.auth);const routes = [GET(path,- async (request, args) => await authenticateMcpRequest(request, args, input.auth, oauth),+ async (request, args) =>+ await authenticateMcpRequest(request, args, input.auth, oauth, publish),),POST(path,- async (request, args) => await authenticateMcpRequest(request, args, input.auth, oauth),+ async (request, args) =>+ await authenticateMcpRequest(request, args, input.auth, oauth, publish),),DELETE(path,- async (request, args) => await authenticateMcpRequest(request, args, input.auth, oauth),+ async (request, args) =>+ await authenticateMcpRequest(request, args, input.auth, oauth, publish),),];if (oauth !== undefined) {@@ -326,6 +349,7 @@ async function authenticateMcpRequest(args: RouteHandlerArgs,policy: AuthFn<Request> | readonly AuthFn<Request>[],oauth: OAuthResourceOptions | undefined,+ publish: McpPublishOptions,): Promise<Response> {const securityFailure = validateMcpHttpRequest(request);if (securityFailure !== undefined) return securityFailure;@@ -333,13 +357,19 @@ async function authenticateMcpRequest(if (auth instanceof Response) {return oauth === undefined ? auth : addResourceChallenge(auth, request, oauth);}- return await handleMcpRequest(request, args, auth);+ return await handleMcpRequest(request, args, auth, publish);+}++interface McpPublishOptions {+ readonly agent: boolean;+ readonly tools: boolean;}async function handleMcpRequest(request: Request,args: RouteHandlerArgs,auth: import("#channel/types.js").SessionAuthContext,+ publish: McpPublishOptions,): Promise<Response> {const createSession = readRouteSessionCreator(args);const channelName = readRouteChannelName(args);@@ -365,15 +395,25 @@ async function handleMcpRequest(createSession,from: args.from,});+ const agentTools = publish.agent+ ? createInvocationTools(+ execution,+ description,+ auth.authenticator === "none" && auth.principalType === "anonymous",+ )+ : [];+ const publishedTools = publish.tools+ ? createPublishedTools({+ invokeTool: args.invokeTool,+ reserved: new Set(agentTools.map((tool) => tool.name)),+ tools: (await args.describe()).tools,+ })+ : [];return await createMcpStreamableHttpServer({authenticate: async () => auth,- instructions: MCP_SERVER_INSTRUCTIONS,+ instructions: publish.agent ? MCP_SERVER_INSTRUCTIONS : undefined,name: agentInfo.agent.name,- tools: createInvocationTools(- execution,- description,- auth.authenticator === "none" && auth.principalType === "anonymous",- ),+ tools: [...agentTools, ...publishedTools],version: resolveInstalledPackageInfo().version,})(request);}