effect-agent 0.1.0-beta.136 → 0.1.0-beta.138
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -83,6 +83,19 @@ const ServerRequest = Schema.Struct({
|
|
|
83
83
|
});
|
|
84
84
|
const isServerRequest = Schema.is(ServerRequest);
|
|
85
85
|
const isJsonRpcRequest = (message) => isServerRequest(message);
|
|
86
|
+
/** Effect RPC's tracing extensions are not part of MCP's strict JSON-RPC request shape. */
|
|
87
|
+
const mcpWireMessage = (message) => {
|
|
88
|
+
if (!Predicate.hasProperty(message, "_tag") || message._tag !== "Request") return message;
|
|
89
|
+
const payload = Predicate.hasProperty(message, "payload") ? message.payload : void 0;
|
|
90
|
+
return {
|
|
91
|
+
...message,
|
|
92
|
+
payload: payload === null ? void 0 : payload,
|
|
93
|
+
traceId: void 0,
|
|
94
|
+
spanId: void 0,
|
|
95
|
+
sampled: void 0,
|
|
96
|
+
headers: []
|
|
97
|
+
};
|
|
98
|
+
};
|
|
86
99
|
/** JSON-RPC error a client returns for a server-initiated request it does not serve. */
|
|
87
100
|
const declineServerRequest = (request) => ({
|
|
88
101
|
_tag: "Exit",
|
|
@@ -183,7 +196,7 @@ const makeHttpProtocol = Effect.fn("McpHttpTransport.protocol")(function* (optio
|
|
|
183
196
|
yield* Effect.addFinalizer(() => sessionId === void 0 ? Effect.void : client.execute(HttpClientRequest.delete(url).pipe(HttpClientRequest.setHeaders(transportHeaders()))).pipe(Effect.ignore));
|
|
184
197
|
return yield* RpcClient.Protocol.make((writeResponse) => Effect.sync(() => {
|
|
185
198
|
const encode = (message) => Effect.suspend(() => {
|
|
186
|
-
const encoded = parser.encode(message);
|
|
199
|
+
const encoded = parser.encode(mcpWireMessage(message));
|
|
187
200
|
return typeof encoded === "string" ? Effect.succeed(encoded) : Effect.fail(protocolDefect("Could not encode an MCP JSON-RPC message"));
|
|
188
201
|
});
|
|
189
202
|
const deliver = (clientId, data) => Effect.suspend(() => {
|
|
@@ -318,7 +331,7 @@ const makeStdioProtocol = Effect.fn("McpStdioTransport.protocol")(function* (opt
|
|
|
318
331
|
});
|
|
319
332
|
const enqueue = (message) => Effect.suspend(() => {
|
|
320
333
|
if (closed !== void 0) return Effect.fail(closed);
|
|
321
|
-
const encoded = parser.encode(message);
|
|
334
|
+
const encoded = parser.encode(mcpWireMessage(message));
|
|
322
335
|
if (typeof encoded !== "string") return Effect.fail(protocolDefect("Could not encode an MCP JSON-RPC message"));
|
|
323
336
|
return Queue.offer(outbound, encoded).pipe(Effect.asVoid);
|
|
324
337
|
});
|
|
@@ -378,7 +391,7 @@ const makeMcpTool = (tool, trustToolAnnotations) => {
|
|
|
378
391
|
success: McpToolResult,
|
|
379
392
|
failure: McpToolCallFailed,
|
|
380
393
|
failureMode: "return"
|
|
381
|
-
});
|
|
394
|
+
}).annotate(Tool.Strict, false);
|
|
382
395
|
const title = tool.title ?? tool.annotations?.title;
|
|
383
396
|
if (title !== void 0) dynamic = dynamic.annotate(Tool.Title, title);
|
|
384
397
|
dynamic = dynamic.annotate(McpToolOutputSchema, Option.fromNullishOr(tool.outputSchema));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"McpClient.mjs","names":[],"sources":["../../src/capabilities/McpClient.ts"],"sourcesContent":["import {\n Cause,\n Context,\n Effect,\n Layer,\n Option,\n Predicate,\n Queue,\n Schema,\n Scope,\n Stream,\n} from \"effect\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\nimport * as McpProtocol from \"effect/unstable/ai/McpProtocol\";\nimport * as McpSchema from \"effect/unstable/ai/McpSchema\";\nimport {\n Headers,\n HttpClient,\n HttpClientRequest,\n type HttpClientResponse,\n} from \"effect/unstable/http\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\nimport { RpcClient, RpcClientError, type RpcMessage, RpcSerialization } from \"effect/unstable/rpc\";\n\nimport { utf8ByteLength } from \"../core/internal/utf8.ts\";\nimport { ToolExecutionClass, type ToolExecutionClassValue } from \"../engine/DurableStep.ts\";\nimport {\n McpConnectionError,\n McpConnector,\n type McpConnectedServer,\n type McpConnectionRequest,\n McpServerIdentity,\n McpToolOutputSchema,\n} from \"./Mcp.ts\";\n\n// ---------------------------------------------------------------------------\n// MCP client: native Effect AI MCP schemas and protocol adapters, the Effect\n// RPC client, and Effect HTTP / child-process services connect an Agent to a\n// remote MCP server. Discovered tools become dynamic Effect AI Tools whose\n// handlers forward `tools/call`; `connectMcp` still applies every discovery\n// bound before the Toolkit reaches Agent context.\n// ---------------------------------------------------------------------------\n\n/** Largest single JSON-RPC message a transport accepts from a server by default. */\nconst DEFAULT_MAX_MESSAGE_BYTES = 4 * 1024 * 1024;\n/** Bounded `tools/list` pagination: a server cannot keep a client walking cursors forever. */\nconst MAX_TOOL_LIST_PAGES = 64;\nconst MCP_SESSION_ID_HEADER = \"mcp-session-id\";\nconst MCP_PROTOCOL_VERSION_HEADER = \"mcp-protocol-version\";\nconst JSON_RPC_METHOD_NOT_FOUND = -32601;\n\n/**\n * The protocol revisions this client negotiates, as implemented by Effect AI's\n * native MCP protocol adapters. The newest revision is offered first; a server\n * answering with any other listed revision is accepted, anything else fails.\n */\nexport const McpClientProtocolVersion = Schema.Literals([\n McpProtocol.v2025_11_25.protocolVersion,\n McpProtocol.v2025_06_18.protocolVersion,\n McpProtocol.v2025_03_26.protocolVersion,\n McpProtocol.v2024_11_05.protocolVersion,\n]);\n\nexport type McpClientProtocolVersion = typeof McpClientProtocolVersion.Type;\n\nconst OFFERED_PROTOCOL_VERSION: McpClientProtocolVersion = McpProtocol.v2025_11_25.protocolVersion;\n\n/** Identity this client presents to servers during `initialize`. */\nexport const defaultMcpClientInfo = McpSchema.Implementation.make({\n name: \"effect-agent\",\n version: \"1.0.0\",\n});\n\n/**\n * The model-visible result of a remote MCP tool call: the server's content\n * blocks and, when the tool declares an `outputSchema`, its structured result.\n * A result with `isError` never becomes this value; it fails the Tool Call.\n */\nexport class McpToolResult extends Schema.Class<McpToolResult>(\n \"@effect-agent/capabilities/McpToolResult\",\n)({\n content: Schema.Array(McpSchema.ContentBlock),\n structuredContent: Schema.optionalKey(Schema.Json),\n}) {}\n\n/**\n * Typed failure of one remote MCP tool call. `tool-error` carries the server's\n * error content; the other reasons describe why no trustworthy result exists.\n * None of them claims the remote effect did not happen.\n */\nexport class McpToolCallFailed extends Schema.TaggedError<McpToolCallFailed>()(\n \"McpToolCallFailed\",\n {\n serverId: Schema.NonEmptyString,\n tool: Schema.NonEmptyString,\n reason: Schema.Literals([\"tool-error\", \"invalid-arguments\", \"protocol-error\", \"transport\"]),\n message: Schema.String,\n content: Schema.optionalKey(Schema.Array(McpSchema.ContentBlock)),\n },\n) {}\n\n/**\n * One reachable MCP server. `protocol` acquires a JSON-RPC transport in the\n * caller's Scope; `R` names the platform services that transport needs so the\n * connector Layer keeps them in its requirements.\n */\nexport interface McpServerTransport<R = never> {\n readonly serverId: string;\n /**\n * Whether the server's `readOnlyHint`, `idempotentHint`, and\n * `destructiveHint` may set the framework execution class of its tools.\n * Hints are server-declared and untrusted, so the default leaves every\n * remote tool `uncertain`.\n */\n readonly trustToolAnnotations: boolean;\n readonly protocol: Effect.Effect<\n RpcClient.Protocol[\"Service\"],\n McpConnectionError,\n Scope.Scope | R\n >;\n}\n\n/** Streamable HTTP server address. Header values may carry credentials the application owns. */\nexport interface McpHttpTransportOptions {\n readonly serverId: string;\n readonly url: string;\n readonly headers?: Headers.Input | undefined;\n /** Largest accepted response message. Defaults to 4 MiB. */\n readonly maxMessageBytes?: number | undefined;\n readonly trustToolAnnotations?: boolean | undefined;\n}\n\n/** A local MCP server process speaking newline-delimited JSON-RPC on stdio. */\nexport interface McpStdioTransportOptions {\n readonly serverId: string;\n readonly command: string;\n readonly args?: ReadonlyArray<string> | undefined;\n readonly cwd?: string | undefined;\n readonly env?: Readonly<Record<string, string>> | undefined;\n /** Largest accepted stdout frame. Defaults to 4 MiB. */\n readonly maxMessageBytes?: number | undefined;\n readonly trustToolAnnotations?: boolean | undefined;\n}\n\nconst isNotificationTag = (tag: string): boolean => tag.startsWith(\"notifications/\");\nconst isRpcClientError = Schema.is(RpcClientError.RpcClientError);\n\nconst protocolDefect = (message: string, cause?: unknown): RpcClientError.RpcClientError =>\n new RpcClientError.RpcClientError({\n reason: new RpcClientError.RpcClientDefect({ message, cause }),\n });\n\nconst InitializeProtocolVersion = Schema.Struct({ protocolVersion: Schema.String });\nconst decodeInitializeProtocolVersion = Schema.decodeUnknownOption(InitializeProtocolVersion);\n\nconst ServerRequest = Schema.Struct({ _tag: Schema.Literal(\"Request\"), tag: Schema.String });\nconst isServerRequest = Schema.is(ServerRequest);\n\nconst isJsonRpcRequest = (message: unknown): message is RpcMessage.RequestEncoded =>\n isServerRequest(message);\n\n/** JSON-RPC error a client returns for a server-initiated request it does not serve. */\nconst declineServerRequest = (\n request: RpcMessage.RequestEncoded,\n): RpcMessage.ResponseExitEncoded => ({\n _tag: \"Exit\",\n requestId: request.id,\n exit: {\n _tag: \"Failure\",\n cause: [\n {\n _tag: \"Fail\",\n error: {\n code: JSON_RPC_METHOD_NOT_FOUND,\n message: `Client does not serve ${request.tag}`,\n },\n },\n ],\n },\n});\n\n/**\n * Routes one decoded JSON-RPC message. Responses reach the RPC client; server\n * notifications are logged; server requests (sampling, elicitation, roots)\n * are declined fail-closed through `respond` because this client serves none.\n */\nconst routeMessage = (\n message: unknown,\n options: {\n readonly clientId: number;\n readonly writeResponse: (\n clientId: number,\n response: RpcMessage.FromServerEncoded,\n ) => Effect.Effect<void>;\n readonly respond: (response: RpcMessage.ResponseExitEncoded) => Effect.Effect<void>;\n readonly onExit: (exit: RpcMessage.ResponseExitEncoded) => void;\n },\n): Effect.Effect<void> => {\n if (isJsonRpcRequest(message)) {\n if (message.isNotification === true) {\n return Effect.logDebug(\"Ignoring MCP server notification\").pipe(\n Effect.annotateLogs({ method: message.tag }),\n );\n }\n\n return options.respond(declineServerRequest(message));\n }\n if (Predicate.hasProperty(message, \"_tag\") && message._tag === \"Exit\") {\n options.onExit(message as RpcMessage.ResponseExitEncoded);\n }\n\n return options.writeResponse(options.clientId, message as RpcMessage.FromServerEncoded);\n};\n\n/** Reads a response body as text while refusing bodies above `maxBytes`. */\nconst readBoundedText = Effect.fn(\"McpHttpTransport.readBoundedText\")(function* (\n response: HttpClientResponse.HttpClientResponse,\n maxBytes: number,\n) {\n const declared = Number(response.headers[\"content-length\"]);\n\n if (Number.isFinite(declared) && declared > maxBytes) {\n return yield* protocolDefect(\n `MCP response of ${declared} bytes exceeds the ${maxBytes} byte message bound`,\n );\n }\n const chunks: Array<string> = [];\n let received = 0;\n\n yield* response.stream.pipe(\n Stream.decodeText(),\n Stream.runForEach((chunk) => {\n received += utf8ByteLength(chunk);\n if (received > maxBytes) {\n return Effect.fail(\n protocolDefect(`MCP response exceeds the ${maxBytes} byte message bound`),\n );\n }\n chunks.push(chunk);\n\n return Effect.void;\n }),\n Effect.mapError((error) =>\n isRpcClientError(error)\n ? error\n : protocolDefect(\"Could not read the MCP HTTP response\", error),\n ),\n );\n\n return chunks.join(\"\");\n});\n\n/**\n * Delivers the `data` of each `text/event-stream` event as it arrives. Only\n * `data` fields carry JSON-RPC messages; `event`, `id`, `retry`, and comment\n * lines are ignored because this client never resumes a stream, so a server\n * retry directive neither ends the stream nor fails the request. At most\n * `maxBytes` of an unterminated event stays buffered.\n */\nconst consumeEventStream = Effect.fn(\"McpHttpTransport.consumeEventStream\")(function* (\n response: HttpClientResponse.HttpClientResponse,\n maxBytes: number,\n deliver: (data: string) => Effect.Effect<void>,\n) {\n let buffer = \"\";\n let pendingBytes = 0;\n\n const dispatchEvent = (block: string): Effect.Effect<void> => {\n const data = block\n .split(/\\r?\\n/)\n .filter((line) => line.startsWith(\"data:\"))\n .map((line) => line.slice(\"data:\".length).replace(/^ /, \"\"))\n .join(\"\\n\");\n\n return data.length === 0 ? Effect.void : deliver(data);\n };\n\n const drain = (final: boolean): Effect.Effect<void> =>\n Effect.suspend(() => {\n const blocks: Array<string> = [];\n\n while (true) {\n const match = /\\r?\\n\\r?\\n/.exec(buffer);\n\n if (match === null) break;\n blocks.push(buffer.slice(0, match.index));\n buffer = buffer.slice(match.index + match[0].length);\n }\n if (final && buffer.length > 0) {\n blocks.push(buffer);\n buffer = \"\";\n }\n pendingBytes = utf8ByteLength(buffer);\n\n return Effect.forEach(blocks, dispatchEvent, { discard: true });\n });\n\n yield* response.stream.pipe(\n Stream.decodeText(),\n Stream.runForEach((chunk) => {\n buffer += chunk;\n pendingBytes += utf8ByteLength(chunk);\n if (pendingBytes > maxBytes) {\n return Effect.fail(protocolDefect(`MCP event stream buffered more than ${maxBytes} bytes`));\n }\n\n return drain(false);\n }),\n Effect.mapError((error) =>\n isRpcClientError(error)\n ? error\n : protocolDefect(\"Could not read the MCP event stream\", error),\n ),\n );\n yield* drain(true);\n});\n\nconst makeHttpProtocol = Effect.fn(\"McpHttpTransport.protocol\")(function* (\n options: McpHttpTransportOptions,\n) {\n const client = yield* HttpClient.HttpClient;\n const serialization = RpcSerialization.jsonRpc();\n const parser = serialization.makeUnsafe();\n const maxMessageBytes = options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES;\n const configuredHeaders = Headers.fromInput(options.headers);\n const url = options.url;\n let sessionId: string | undefined;\n let protocolVersion: string | undefined;\n let initializeRequestId: string | number | undefined;\n /** Request ids whose JSON-RPC response has been delivered. */\n const answered = new Set<string | number>();\n\n const transportHeaders = (): Headers.Headers =>\n Headers.merge(\n configuredHeaders,\n Headers.fromInput({\n accept: \"application/json, text/event-stream\",\n ...(sessionId === undefined ? {} : { [MCP_SESSION_ID_HEADER]: sessionId }),\n ...(protocolVersion === undefined\n ? {}\n : { [MCP_PROTOCOL_VERSION_HEADER]: protocolVersion }),\n }),\n );\n\n const post = (body: string) =>\n client\n .execute(\n HttpClientRequest.post(url).pipe(\n HttpClientRequest.setHeaders(transportHeaders()),\n HttpClientRequest.bodyText(body, \"application/json\"),\n ),\n )\n .pipe(\n Effect.mapError((error) =>\n protocolDefect(`MCP HTTP request to ${options.serverId} failed`, error),\n ),\n );\n\n // Ending the session is a courtesy to the server; the Scope owns the client.\n yield* Effect.addFinalizer(() =>\n sessionId === undefined\n ? Effect.void\n : client\n .execute(\n HttpClientRequest.delete(url).pipe(HttpClientRequest.setHeaders(transportHeaders())),\n )\n .pipe(Effect.ignore),\n );\n\n return yield* RpcClient.Protocol.make((writeResponse) =>\n Effect.sync(() => {\n const encode = (message: unknown): Effect.Effect<string, RpcClientError.RpcClientError> =>\n Effect.suspend(() => {\n const encoded = parser.encode(message);\n\n return typeof encoded === \"string\"\n ? Effect.succeed(encoded)\n : Effect.fail(protocolDefect(\"Could not encode an MCP JSON-RPC message\"));\n });\n\n const deliver = (clientId: number, data: string): Effect.Effect<void> =>\n Effect.suspend(() => {\n let messages: ReadonlyArray<unknown>;\n\n try {\n messages = parser.decode(data);\n } catch (cause) {\n return writeResponse(clientId, {\n _tag: \"ClientProtocolError\",\n error: protocolDefect(\"Could not decode an MCP JSON-RPC message\", cause),\n });\n }\n\n return Effect.forEach(\n messages,\n (message) =>\n routeMessage(message, {\n clientId,\n writeResponse,\n respond: (response) => encode(response).pipe(Effect.flatMap(post), Effect.ignore),\n onExit: (exit) => {\n answered.add(exit.requestId);\n if (exit.requestId !== initializeRequestId || exit.exit._tag !== \"Success\") {\n return;\n }\n const decoded = decodeInitializeProtocolVersion(exit.exit.value);\n\n if (Option.isSome(decoded)) protocolVersion = decoded.value.protocolVersion;\n },\n }),\n { discard: true },\n );\n });\n\n /**\n * Posts one message and delivers whatever the server answers. A request\n * whose HTTP exchange completes without a JSON-RPC response for its id\n * (for example a `202`, an `id: null` error, or a stream that ends\n * early) fails that request instead of leaving its caller waiting.\n */\n const dispatch = Effect.fn(\"McpHttpTransport.dispatch\")(function* (\n clientId: number,\n message: unknown,\n requestId?: string | number,\n ) {\n const response = yield* post(yield* encode(message));\n const responseSession = response.headers[MCP_SESSION_ID_HEADER];\n\n if (responseSession !== undefined) sessionId = responseSession;\n if (response.status < 200 || response.status >= 300) {\n return yield* protocolDefect(\n `MCP server ${options.serverId} answered HTTP ${response.status}`,\n );\n }\n const contentType = response.headers[\"content-type\"] ?? \"\";\n\n if (response.status !== 202 && response.status !== 204) {\n if (contentType.startsWith(\"text/event-stream\")) {\n yield* consumeEventStream(response, maxMessageBytes, (data) => deliver(clientId, data));\n } else {\n const text = yield* readBoundedText(response, maxMessageBytes);\n\n if (text.length > 0) yield* deliver(clientId, text);\n }\n }\n if (requestId !== undefined && !answered.has(requestId)) {\n yield* writeResponse(clientId, {\n _tag: \"Exit\",\n requestId,\n exit: {\n _tag: \"Failure\",\n cause: [\n {\n _tag: \"Die\",\n defect: `MCP server ${options.serverId} closed the HTTP exchange without answering request ${String(requestId)}`,\n },\n ],\n },\n });\n }\n answered.delete(requestId ?? \"\");\n });\n\n const send: RpcClient.Protocol[\"Service\"][\"send\"] = (clientId, request) => {\n switch (request._tag) {\n case \"Request\": {\n if (isNotificationTag(request.tag)) {\n return dispatch(clientId, { ...request, isNotification: true });\n }\n if (request.tag === \"initialize\") initializeRequestId = request.id;\n\n return dispatch(clientId, request, request.id);\n }\n case \"Interrupt\": {\n return dispatch(clientId, {\n _tag: \"Request\",\n id: request.requestId,\n tag: \"notifications/cancelled\",\n payload: { requestId: request.requestId },\n headers: [],\n isNotification: true,\n } satisfies RpcMessage.RequestEncoded);\n }\n case \"Ack\":\n case \"Ping\":\n case \"Eof\": {\n return Effect.void;\n }\n }\n };\n\n return {\n send,\n supportsAck: false,\n supportsTransferables: false,\n codecFor: serialization.codecFor,\n };\n }),\n );\n});\n\nconst makeStdioProtocol = Effect.fn(\"McpStdioTransport.protocol\")(function* (\n options: McpStdioTransportOptions,\n) {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n const maxMessageBytes = options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES;\n const serialization = RpcSerialization.ndJsonRpc({ maxBufferSize: maxMessageBytes });\n const parser = serialization.makeUnsafe();\n\n const handle = yield* spawner\n .spawn(\n ChildProcess.make(options.command, [...(options.args ?? [])], {\n ...(options.cwd === undefined ? {} : { cwd: options.cwd }),\n ...(options.env === undefined ? {} : { env: options.env, extendEnv: true }),\n }),\n )\n .pipe(\n Effect.mapError((cause) =>\n McpConnectionError.make({\n serverId: options.serverId,\n message: `Could not start the MCP server process for ${options.serverId}`,\n cause,\n }),\n ),\n );\n\n const outbound = yield* Queue.unbounded<string>();\n // Once the process is gone every later send fails immediately instead of\n // queueing behind a writer that no longer exists.\n let closed: RpcClientError.RpcClientError | undefined;\n\n const closedWith = (message: string, cause?: unknown): RpcClientError.RpcClientError =>\n (closed ??= protocolDefect(message, cause));\n\n yield* Stream.fromQueue(outbound).pipe(\n Stream.encodeText,\n Stream.run(handle.stdin),\n Effect.matchCauseEffect({\n onSuccess: () =>\n Effect.sync(() => closedWith(`MCP server process ${options.serverId} closed stdin`)),\n onFailure: (cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.void\n : Effect.sync(() =>\n closedWith(\n `Writing to MCP server process ${options.serverId} failed`,\n Cause.squash(cause),\n ),\n ),\n }),\n Effect.forkScoped,\n );\n yield* handle.stderr.pipe(\n Stream.decodeText(),\n Stream.splitLines,\n Stream.runForEach((line) => Effect.logDebug(line)),\n Effect.ignore,\n Effect.annotateLogs({ mcpServerId: options.serverId, stream: \"stderr\" }),\n Effect.forkScoped,\n );\n\n return yield* RpcClient.Protocol.make(\n Effect.fnUntraced(function* (writeResponse, clientIds) {\n const broadcast = (error: RpcClientError.RpcClientError) =>\n Effect.forEach(\n clientIds,\n (clientId) => writeResponse(clientId, { _tag: \"ClientProtocolError\", error }),\n { discard: true },\n );\n\n const deliver = (chunk: Uint8Array): Effect.Effect<void> =>\n Effect.suspend(() => {\n let messages: ReadonlyArray<unknown>;\n\n try {\n messages = parser.decode(chunk);\n } catch (cause) {\n return broadcast(protocolDefect(\"Could not decode an MCP stdio frame\", cause));\n }\n\n return Effect.forEach(\n messages,\n (message) =>\n Effect.forEach(\n clientIds,\n (clientId) =>\n routeMessage(message, {\n clientId,\n writeResponse,\n respond: (response) => enqueue(response).pipe(Effect.ignore),\n onExit: () => {},\n }),\n { discard: true },\n ),\n { discard: true },\n );\n });\n\n const enqueue = (message: unknown): Effect.Effect<void, RpcClientError.RpcClientError> =>\n Effect.suspend(() => {\n if (closed !== undefined) return Effect.fail(closed);\n const encoded = parser.encode(message);\n\n if (typeof encoded !== \"string\") {\n return Effect.fail(protocolDefect(\"Could not encode an MCP JSON-RPC message\"));\n }\n\n return Queue.offer(outbound, encoded).pipe(Effect.asVoid);\n });\n\n yield* handle.stdout.pipe(\n Stream.runForEach(deliver),\n Effect.matchCauseEffect({\n onSuccess: () =>\n broadcast(closedWith(`MCP server process ${options.serverId} closed stdout`)),\n onFailure: (cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.void\n : broadcast(\n closedWith(\n `Reading MCP server process ${options.serverId} failed`,\n Cause.squash(cause),\n ),\n ),\n }),\n Effect.forkScoped,\n );\n\n const send: RpcClient.Protocol[\"Service\"][\"send\"] = (_clientId, request) => {\n switch (request._tag) {\n case \"Request\": {\n return enqueue(\n isNotificationTag(request.tag) ? { ...request, isNotification: true } : request,\n );\n }\n case \"Interrupt\": {\n return enqueue({\n _tag: \"Request\",\n id: request.requestId,\n tag: \"notifications/cancelled\",\n payload: { requestId: request.requestId },\n headers: [],\n isNotification: true,\n } satisfies RpcMessage.RequestEncoded);\n }\n case \"Ack\":\n case \"Ping\":\n case \"Eof\": {\n return Effect.void;\n }\n }\n };\n\n return {\n send,\n supportsAck: false,\n supportsTransferables: false,\n codecFor: serialization.codecFor,\n };\n }),\n );\n});\n\n/** Streamable HTTP transport for one remote MCP server; requires `HttpClient`. */\nexport const McpHttpTransport = {\n make: (options: McpHttpTransportOptions): McpServerTransport<HttpClient.HttpClient> => ({\n serverId: options.serverId,\n trustToolAnnotations: options.trustToolAnnotations ?? false,\n protocol: makeHttpProtocol(options),\n }),\n} as const;\n\n/** stdio transport for one local MCP server process; requires `ChildProcessSpawner`. */\nexport const McpStdioTransport = {\n make: (\n options: McpStdioTransportOptions,\n ): McpServerTransport<ChildProcessSpawner.ChildProcessSpawner> => ({\n serverId: options.serverId,\n trustToolAnnotations: options.trustToolAnnotations ?? false,\n protocol: makeStdioProtocol(options),\n }),\n} as const;\n\n/**\n * Effect AI Tool derived from one discovered MCP tool. Its parameters are the\n * server's JSON Schema, so handlers receive `unknown` and the server validates\n * arguments; `Tool.getJsonSchema` still advertises the discovered schema. A\n * failed call returns `McpToolCallFailed` to the model as a failed tool result.\n */\nexport type McpTool = Tool.Tool<\n string,\n {\n readonly parameters: typeof Schema.Unknown;\n readonly success: typeof McpToolResult;\n readonly failure: typeof McpToolCallFailed;\n readonly failureMode: \"return\";\n }\n>;\n\n/** Toolkit of discovered MCP tools; every member forwards `tools/call` to its server. */\nexport type McpToolkit = Toolkit.Toolkit<Record<string, McpTool>>;\n\nconst executionClassFor = (\n annotations: McpSchema.ToolAnnotations | undefined,\n): ToolExecutionClassValue => {\n if (annotations === undefined) return \"uncertain\";\n if (annotations.readOnlyHint) return \"readonly\";\n if (annotations.idempotentHint && !annotations.destructiveHint) return \"idempotent\";\n\n return \"uncertain\";\n};\n\nconst makeMcpTool = (tool: McpSchema.Tool, trustToolAnnotations: boolean): McpTool => {\n let dynamic: McpTool = Tool.dynamic(tool.name, {\n ...(tool.description === undefined ? {} : { description: tool.description }),\n parameters: tool.inputSchema,\n success: McpToolResult,\n failure: McpToolCallFailed,\n // MCP reports tool errors inside results so the model can self-correct;\n // `return` hands the typed failure to the model the same way.\n failureMode: \"return\",\n });\n\n const title = tool.title ?? tool.annotations?.title;\n\n if (title !== undefined) dynamic = dynamic.annotate(Tool.Title, title);\n dynamic = dynamic.annotate(McpToolOutputSchema, Option.fromNullishOr(tool.outputSchema));\n if (tool.annotations !== undefined) {\n dynamic = dynamic\n .annotate(Tool.Readonly, tool.annotations.readOnlyHint)\n .annotate(Tool.Destructive, tool.annotations.destructiveHint)\n .annotate(Tool.Idempotent, tool.annotations.idempotentHint)\n .annotate(Tool.OpenWorld, tool.annotations.openWorldHint);\n }\n if (trustToolAnnotations) {\n dynamic = dynamic.annotate(ToolExecutionClass, executionClassFor(tool.annotations));\n }\n\n return dynamic;\n};\n\nconst ToolArguments = Schema.Record(Schema.String, Schema.Json);\nconst decodeToolArguments = Schema.decodeUnknownEffect(ToolArguments);\n\nconst errorText = (content: ReadonlyArray<typeof McpSchema.ContentBlock.Type>): string =>\n content\n .flatMap((block) => (block.type === \"text\" ? [block.text] : []))\n .join(\"\\n\")\n .slice(0, 4 * 1024);\n\nconst describeDefect = (defect: unknown): string =>\n (Predicate.hasProperty(defect, \"message\") && Predicate.isString(defect.message)\n ? defect.message\n : String(defect)\n ).slice(0, 4 * 1024);\n\nconst connectionError = (serverId: string, message: string) => (cause: unknown) =>\n McpConnectionError.make({ serverId, message, cause });\n\n/**\n * Keeps every non-interrupt outcome of one protocol step typed: expected\n * failures and defects (such as an undecodable server reply) both become the\n * connection error, so a misbehaving server cannot crash the connector.\n */\nconst failClosed =\n (serverId: string, message: string) =>\n <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, McpConnectionError, R> =>\n self.pipe(\n Effect.mapError(connectionError(serverId, message)),\n Effect.catchDefect((defect) => Effect.fail(connectionError(serverId, message)(defect))),\n );\n\nconst connectServer = Effect.fn(\"McpClient.connect\")(function* <R>(\n transport: McpServerTransport<R>,\n request: McpConnectionRequest,\n clientInfo: McpSchema.Implementation,\n): Effect.fn.Return<McpConnectedServer, McpConnectionError, Scope.Scope | R> {\n const serverId = transport.serverId;\n const protocol = yield* transport.protocol;\n\n const client = yield* RpcClient.make(McpSchema.ClientRpcs, {\n spanPrefix: \"McpClient\",\n spanAttributes: { \"mcp.server_id\": serverId },\n }).pipe(Effect.provideService(RpcClient.Protocol, protocol));\n\n const initialized = yield* client\n .initialize({\n protocolVersion: OFFERED_PROTOCOL_VERSION,\n capabilities: McpSchema.ClientCapabilities.make({}),\n clientInfo,\n })\n .pipe(failClosed(serverId, `MCP initialize with ${serverId} failed`));\n\n const negotiated = yield* Schema.decodeUnknownEffect(McpClientProtocolVersion)(\n initialized.protocolVersion,\n ).pipe(\n Effect.mapError(\n connectionError(\n serverId,\n `MCP server ${serverId} negotiated unsupported protocol version '${initialized.protocolVersion}'`,\n ),\n ),\n );\n\n yield* Effect.annotateCurrentSpan({ \"mcp.protocol_version\": negotiated });\n yield* client[\"notifications/initialized\"](undefined, { discard: true }).pipe(\n failClosed(serverId, `Could not acknowledge MCP initialization with ${serverId}`),\n );\n\n const tools: Array<McpSchema.Tool> = [];\n let cursor: string | undefined;\n let pages = 0;\n\n do {\n const page = yield* client[\"tools/list\"](\n cursor === undefined ? undefined : McpSchema.PaginatedRequestMeta.make({ cursor }),\n ).pipe(failClosed(serverId, `MCP tools/list with ${serverId} failed`));\n\n tools.push(...page.tools);\n cursor = page.nextCursor;\n pages += 1;\n // `validateMcpDiscovery` rejects the count; stop paying for more pages.\n if (tools.length > request.maxToolCount) break;\n if (cursor !== undefined && pages >= MAX_TOOL_LIST_PAGES) {\n return yield* McpConnectionError.make({\n serverId,\n message: `MCP server ${serverId} paginated tools/list beyond ${MAX_TOOL_LIST_PAGES} pages`,\n });\n }\n } while (cursor !== undefined);\n\n const callTool = Effect.fn(\"McpClient.callTool\")(function* (name: string, params: unknown) {\n const args = yield* decodeToolArguments(params ?? {}).pipe(\n Effect.mapError((cause) =>\n McpToolCallFailed.make({\n serverId,\n tool: name,\n reason: \"invalid-arguments\",\n message: `MCP tool arguments must be a JSON object: ${cause.message}`,\n }),\n ),\n );\n\n const result = yield* client[\"tools/call\"]({ name, arguments: args }).pipe(\n Effect.mapError((error) =>\n McpToolCallFailed.make({\n serverId,\n tool: name,\n reason: isRpcClientError(error) ? \"transport\" : \"protocol-error\",\n message: error.message,\n }),\n ),\n // A JSON-RPC error the MCP error union cannot decode (or any other\n // malformed reply) surfaces as a defect from the RPC client. It is still\n // the server's answer, so it reaches the model as a failed tool result\n // rather than aborting the batch.\n Effect.catchDefect((defect) =>\n Effect.fail(\n McpToolCallFailed.make({\n serverId,\n tool: name,\n reason: \"protocol-error\",\n message: describeDefect(defect),\n }),\n ),\n ),\n );\n\n if (result.isError === true) {\n return yield* McpToolCallFailed.make({\n serverId,\n tool: name,\n reason: \"tool-error\",\n message: errorText(result.content),\n content: result.content,\n });\n }\n\n return McpToolResult.make({\n content: result.content,\n ...(result.structuredContent === undefined\n ? {}\n : { structuredContent: result.structuredContent }),\n });\n });\n\n const toolkit: McpToolkit = yield* Effect.try({\n try: () =>\n Toolkit.make(...tools.map((tool) => makeMcpTool(tool, transport.trustToolAnnotations))),\n catch: connectionError(\n serverId,\n `MCP server ${serverId} advertised tools that cannot form a Toolkit`,\n ),\n });\n\n const handlers = toolkit.toLayer(\n Object.fromEntries(\n tools.map((tool) => [tool.name, (params: unknown) => callTool(tool.name, params)] as const),\n ),\n );\n\n return {\n identity: McpServerIdentity.make({ serverId, implementation: initialized.serverInfo }),\n capabilities: initialized.capabilities,\n tools,\n toolkit,\n handlers,\n } satisfies McpConnectedServer;\n});\n\n/** Platform services one transport needs, as declared by `McpServerTransport<R>`. */\nexport type McpTransportRequirements<Transport> =\n Transport extends McpServerTransport<infer R> ? R : never;\n\nconst makeConnectorLayer = <R>(\n transports: ReadonlyArray<McpServerTransport<R>>,\n options: { readonly clientInfo?: McpSchema.Implementation | undefined } | undefined,\n): Layer.Layer<McpConnector, never, R> =>\n Layer.effect(McpConnector)(\n Effect.gen(function* () {\n const services = yield* Effect.context<R>();\n const byServerId = new Map(transports.map((transport) => [transport.serverId, transport]));\n const clientInfo = options?.clientInfo ?? defaultMcpClientInfo;\n\n return McpConnector.of({\n connect: (request) => {\n const transport = byServerId.get(request.serverId);\n\n if (transport === undefined) {\n return Effect.fail(\n McpConnectionError.make({\n serverId: request.serverId,\n message: `No MCP transport is configured for server '${request.serverId}'`,\n }),\n );\n }\n\n // The Layer supplies the transport's platform services, but the\n // connection must live and die with the caller's Scope, never the\n // Layer's.\n return connectServer(transport, request, clientInfo).pipe(\n Effect.updateContext((caller: Context.Context<Scope.Scope>) =>\n Context.merge(Context.merge(caller, services), Context.pick(Scope.Scope)(caller)),\n ),\n );\n },\n });\n }),\n );\n\n/**\n * `McpConnector` over real transports. Each `connect` acquires the transport\n * in the caller's Scope, negotiates a protocol revision, lists tools within the\n * request bounds, and returns dynamic Effect AI Tools plus the handler Layer\n * that forwards their calls. The Layer requires the union of every\n * transport's platform services.\n */\nexport const layer = <const Transports extends ReadonlyArray<McpServerTransport<unknown>>>(\n transports: Transports,\n options?: { readonly clientInfo?: McpSchema.Implementation | undefined },\n): Layer.Layer<McpConnector, never, McpTransportRequirements<Transports[number]>> =>\n makeConnectorLayer(\n // Type-level only: each element declares its own `R`, and the Layer\n // requires their union. Nothing about the values changes.\n transports as ReadonlyArray<McpServerTransport<McpTransportRequirements<Transports[number]>>>,\n options,\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAM,4BAA4B;;AAElC,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAC9B,MAAM,8BAA8B;AACpC,MAAM,4BAA4B;;;;;;AAOlC,MAAa,2BAA2B,OAAO,SAAS;CACtD,YAAY,YAAY;CACxB,YAAY,YAAY;CACxB,YAAY,YAAY;CACxB,YAAY,YAAY;AAC1B,CAAC;AAID,MAAM,2BAAqD,YAAY,YAAY;;AAGnF,MAAa,uBAAuB,UAAU,eAAe,KAAK;CAChE,MAAM;CACN,SAAS;AACX,CAAC;;;;;;AAOD,IAAa,gBAAb,cAAmC,OAAO,MACxC,0CACF,CAAC,CAAC;CACA,SAAS,OAAO,MAAM,UAAU,YAAY;CAC5C,mBAAmB,OAAO,YAAY,OAAO,IAAI;AACnD,CAAC,CAAC,CAAC,CAAC;;;;;;AAOJ,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA;CACE,UAAU,OAAO;CACjB,MAAM,O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sBACJ,YACA,YAEA,MAAM,OAAO,YAAY,CAAC,CACxB,OAAO,IAAI,aAAa;CACtB,MAAM,WAAW,OAAO,OAAO,QAAW;CAC1C,MAAM,aAAa,IAAI,IAAI,WAAW,KAAK,cAAc,CAAC,UAAU,UAAU,SAAS,CAAC,CAAC;CACzF,MAAM,aAAa,SAAS,cAAc;CAE1C,OAAO,aAAa,GAAG,EACrB,UAAU,YAAY;EACpB,MAAM,YAAY,WAAW,IAAI,QAAQ,QAAQ;EAEjD,IAAI,cAAc,KAAA,GAChB,OAAO,OAAO,KACZ,mBAAmB,KAAK;GACtB,UAAU,QAAQ;GAClB,SAAS,8CAA8C,QAAQ,SAAS;EAC1E,CAAC,CACH;EAMF,OAAO,cAAc,WAAW,SAAS,UAAU,CAAC,CAAC,KACnD,OAAO,eAAe,WACpB,QAAQ,MAAM,QAAQ,MAAM,QAAQ,QAAQ,GAAG,QAAQ,KAAK,MAAM,KAAK,CAAC,CAAC,MAAM,CAAC,CAClF,CACF;CACF,EACF,CAAC;AACH,CAAC,CACH;;;;;;;;AASF,MAAa,SACX,YACA,YAEA,mBAGE,YACA,OACF"}
|
|
1
|
+
{"version":3,"file":"McpClient.mjs","names":[],"sources":["../../src/capabilities/McpClient.ts"],"sourcesContent":["import {\n Cause,\n Context,\n Effect,\n Layer,\n Option,\n Predicate,\n Queue,\n Schema,\n Scope,\n Stream,\n} from \"effect\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\nimport * as McpProtocol from \"effect/unstable/ai/McpProtocol\";\nimport * as McpSchema from \"effect/unstable/ai/McpSchema\";\nimport {\n Headers,\n HttpClient,\n HttpClientRequest,\n type HttpClientResponse,\n} from \"effect/unstable/http\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\nimport { RpcClient, RpcClientError, type RpcMessage, RpcSerialization } from \"effect/unstable/rpc\";\n\nimport { utf8ByteLength } from \"../core/internal/utf8.ts\";\nimport { ToolExecutionClass, type ToolExecutionClassValue } from \"../engine/DurableStep.ts\";\nimport {\n McpConnectionError,\n McpConnector,\n type McpConnectedServer,\n type McpConnectionRequest,\n McpServerIdentity,\n McpToolOutputSchema,\n} from \"./Mcp.ts\";\n\n// ---------------------------------------------------------------------------\n// MCP client: native Effect AI MCP schemas and protocol adapters, the Effect\n// RPC client, and Effect HTTP / child-process services connect an Agent to a\n// remote MCP server. Discovered tools become dynamic Effect AI Tools whose\n// handlers forward `tools/call`; `connectMcp` still applies every discovery\n// bound before the Toolkit reaches Agent context.\n// ---------------------------------------------------------------------------\n\n/** Largest single JSON-RPC message a transport accepts from a server by default. */\nconst DEFAULT_MAX_MESSAGE_BYTES = 4 * 1024 * 1024;\n/** Bounded `tools/list` pagination: a server cannot keep a client walking cursors forever. */\nconst MAX_TOOL_LIST_PAGES = 64;\nconst MCP_SESSION_ID_HEADER = \"mcp-session-id\";\nconst MCP_PROTOCOL_VERSION_HEADER = \"mcp-protocol-version\";\nconst JSON_RPC_METHOD_NOT_FOUND = -32601;\n\n/**\n * The protocol revisions this client negotiates, as implemented by Effect AI's\n * native MCP protocol adapters. The newest revision is offered first; a server\n * answering with any other listed revision is accepted, anything else fails.\n */\nexport const McpClientProtocolVersion = Schema.Literals([\n McpProtocol.v2025_11_25.protocolVersion,\n McpProtocol.v2025_06_18.protocolVersion,\n McpProtocol.v2025_03_26.protocolVersion,\n McpProtocol.v2024_11_05.protocolVersion,\n]);\n\nexport type McpClientProtocolVersion = typeof McpClientProtocolVersion.Type;\n\nconst OFFERED_PROTOCOL_VERSION: McpClientProtocolVersion = McpProtocol.v2025_11_25.protocolVersion;\n\n/** Identity this client presents to servers during `initialize`. */\nexport const defaultMcpClientInfo = McpSchema.Implementation.make({\n name: \"effect-agent\",\n version: \"1.0.0\",\n});\n\n/**\n * The model-visible result of a remote MCP tool call: the server's content\n * blocks and, when the tool declares an `outputSchema`, its structured result.\n * A result with `isError` never becomes this value; it fails the Tool Call.\n */\nexport class McpToolResult extends Schema.Class<McpToolResult>(\n \"@effect-agent/capabilities/McpToolResult\",\n)({\n content: Schema.Array(McpSchema.ContentBlock),\n structuredContent: Schema.optionalKey(Schema.Json),\n}) {}\n\n/**\n * Typed failure of one remote MCP tool call. `tool-error` carries the server's\n * error content; the other reasons describe why no trustworthy result exists.\n * None of them claims the remote effect did not happen.\n */\nexport class McpToolCallFailed extends Schema.TaggedError<McpToolCallFailed>()(\n \"McpToolCallFailed\",\n {\n serverId: Schema.NonEmptyString,\n tool: Schema.NonEmptyString,\n reason: Schema.Literals([\"tool-error\", \"invalid-arguments\", \"protocol-error\", \"transport\"]),\n message: Schema.String,\n content: Schema.optionalKey(Schema.Array(McpSchema.ContentBlock)),\n },\n) {}\n\n/**\n * One reachable MCP server. `protocol` acquires a JSON-RPC transport in the\n * caller's Scope; `R` names the platform services that transport needs so the\n * connector Layer keeps them in its requirements.\n */\nexport interface McpServerTransport<R = never> {\n readonly serverId: string;\n /**\n * Whether the server's `readOnlyHint`, `idempotentHint`, and\n * `destructiveHint` may set the framework execution class of its tools.\n * Hints are server-declared and untrusted, so the default leaves every\n * remote tool `uncertain`.\n */\n readonly trustToolAnnotations: boolean;\n readonly protocol: Effect.Effect<\n RpcClient.Protocol[\"Service\"],\n McpConnectionError,\n Scope.Scope | R\n >;\n}\n\n/** Streamable HTTP server address. Header values may carry credentials the application owns. */\nexport interface McpHttpTransportOptions {\n readonly serverId: string;\n readonly url: string;\n readonly headers?: Headers.Input | undefined;\n /** Largest accepted response message. Defaults to 4 MiB. */\n readonly maxMessageBytes?: number | undefined;\n readonly trustToolAnnotations?: boolean | undefined;\n}\n\n/** A local MCP server process speaking newline-delimited JSON-RPC on stdio. */\nexport interface McpStdioTransportOptions {\n readonly serverId: string;\n readonly command: string;\n readonly args?: ReadonlyArray<string> | undefined;\n readonly cwd?: string | undefined;\n readonly env?: Readonly<Record<string, string>> | undefined;\n /** Largest accepted stdout frame. Defaults to 4 MiB. */\n readonly maxMessageBytes?: number | undefined;\n readonly trustToolAnnotations?: boolean | undefined;\n}\n\nconst isNotificationTag = (tag: string): boolean => tag.startsWith(\"notifications/\");\nconst isRpcClientError = Schema.is(RpcClientError.RpcClientError);\n\nconst protocolDefect = (message: string, cause?: unknown): RpcClientError.RpcClientError =>\n new RpcClientError.RpcClientError({\n reason: new RpcClientError.RpcClientDefect({ message, cause }),\n });\n\nconst InitializeProtocolVersion = Schema.Struct({ protocolVersion: Schema.String });\nconst decodeInitializeProtocolVersion = Schema.decodeUnknownOption(InitializeProtocolVersion);\n\nconst ServerRequest = Schema.Struct({ _tag: Schema.Literal(\"Request\"), tag: Schema.String });\nconst isServerRequest = Schema.is(ServerRequest);\n\nconst isJsonRpcRequest = (message: unknown): message is RpcMessage.RequestEncoded =>\n isServerRequest(message);\n\n/** Effect RPC's tracing extensions are not part of MCP's strict JSON-RPC request shape. */\nconst mcpWireMessage = (message: unknown): unknown => {\n if (!Predicate.hasProperty(message, \"_tag\") || message._tag !== \"Request\") return message;\n const payload = Predicate.hasProperty(message, \"payload\") ? message.payload : undefined;\n\n return {\n ...message,\n payload: payload === null ? undefined : payload,\n traceId: undefined,\n spanId: undefined,\n sampled: undefined,\n headers: [],\n };\n};\n\n/** JSON-RPC error a client returns for a server-initiated request it does not serve. */\nconst declineServerRequest = (\n request: RpcMessage.RequestEncoded,\n): RpcMessage.ResponseExitEncoded => ({\n _tag: \"Exit\",\n requestId: request.id,\n exit: {\n _tag: \"Failure\",\n cause: [\n {\n _tag: \"Fail\",\n error: {\n code: JSON_RPC_METHOD_NOT_FOUND,\n message: `Client does not serve ${request.tag}`,\n },\n },\n ],\n },\n});\n\n/**\n * Routes one decoded JSON-RPC message. Responses reach the RPC client; server\n * notifications are logged; server requests (sampling, elicitation, roots)\n * are declined fail-closed through `respond` because this client serves none.\n */\nconst routeMessage = (\n message: unknown,\n options: {\n readonly clientId: number;\n readonly writeResponse: (\n clientId: number,\n response: RpcMessage.FromServerEncoded,\n ) => Effect.Effect<void>;\n readonly respond: (response: RpcMessage.ResponseExitEncoded) => Effect.Effect<void>;\n readonly onExit: (exit: RpcMessage.ResponseExitEncoded) => void;\n },\n): Effect.Effect<void> => {\n if (isJsonRpcRequest(message)) {\n if (message.isNotification === true) {\n return Effect.logDebug(\"Ignoring MCP server notification\").pipe(\n Effect.annotateLogs({ method: message.tag }),\n );\n }\n\n return options.respond(declineServerRequest(message));\n }\n if (Predicate.hasProperty(message, \"_tag\") && message._tag === \"Exit\") {\n options.onExit(message as RpcMessage.ResponseExitEncoded);\n }\n\n return options.writeResponse(options.clientId, message as RpcMessage.FromServerEncoded);\n};\n\n/** Reads a response body as text while refusing bodies above `maxBytes`. */\nconst readBoundedText = Effect.fn(\"McpHttpTransport.readBoundedText\")(function* (\n response: HttpClientResponse.HttpClientResponse,\n maxBytes: number,\n) {\n const declared = Number(response.headers[\"content-length\"]);\n\n if (Number.isFinite(declared) && declared > maxBytes) {\n return yield* protocolDefect(\n `MCP response of ${declared} bytes exceeds the ${maxBytes} byte message bound`,\n );\n }\n const chunks: Array<string> = [];\n let received = 0;\n\n yield* response.stream.pipe(\n Stream.decodeText(),\n Stream.runForEach((chunk) => {\n received += utf8ByteLength(chunk);\n if (received > maxBytes) {\n return Effect.fail(\n protocolDefect(`MCP response exceeds the ${maxBytes} byte message bound`),\n );\n }\n chunks.push(chunk);\n\n return Effect.void;\n }),\n Effect.mapError((error) =>\n isRpcClientError(error)\n ? error\n : protocolDefect(\"Could not read the MCP HTTP response\", error),\n ),\n );\n\n return chunks.join(\"\");\n});\n\n/**\n * Delivers the `data` of each `text/event-stream` event as it arrives. Only\n * `data` fields carry JSON-RPC messages; `event`, `id`, `retry`, and comment\n * lines are ignored because this client never resumes a stream, so a server\n * retry directive neither ends the stream nor fails the request. At most\n * `maxBytes` of an unterminated event stays buffered.\n */\nconst consumeEventStream = Effect.fn(\"McpHttpTransport.consumeEventStream\")(function* (\n response: HttpClientResponse.HttpClientResponse,\n maxBytes: number,\n deliver: (data: string) => Effect.Effect<void>,\n) {\n let buffer = \"\";\n let pendingBytes = 0;\n\n const dispatchEvent = (block: string): Effect.Effect<void> => {\n const data = block\n .split(/\\r?\\n/)\n .filter((line) => line.startsWith(\"data:\"))\n .map((line) => line.slice(\"data:\".length).replace(/^ /, \"\"))\n .join(\"\\n\");\n\n return data.length === 0 ? Effect.void : deliver(data);\n };\n\n const drain = (final: boolean): Effect.Effect<void> =>\n Effect.suspend(() => {\n const blocks: Array<string> = [];\n\n while (true) {\n const match = /\\r?\\n\\r?\\n/.exec(buffer);\n\n if (match === null) break;\n blocks.push(buffer.slice(0, match.index));\n buffer = buffer.slice(match.index + match[0].length);\n }\n if (final && buffer.length > 0) {\n blocks.push(buffer);\n buffer = \"\";\n }\n pendingBytes = utf8ByteLength(buffer);\n\n return Effect.forEach(blocks, dispatchEvent, { discard: true });\n });\n\n yield* response.stream.pipe(\n Stream.decodeText(),\n Stream.runForEach((chunk) => {\n buffer += chunk;\n pendingBytes += utf8ByteLength(chunk);\n if (pendingBytes > maxBytes) {\n return Effect.fail(protocolDefect(`MCP event stream buffered more than ${maxBytes} bytes`));\n }\n\n return drain(false);\n }),\n Effect.mapError((error) =>\n isRpcClientError(error)\n ? error\n : protocolDefect(\"Could not read the MCP event stream\", error),\n ),\n );\n yield* drain(true);\n});\n\nconst makeHttpProtocol = Effect.fn(\"McpHttpTransport.protocol\")(function* (\n options: McpHttpTransportOptions,\n) {\n const client = yield* HttpClient.HttpClient;\n const serialization = RpcSerialization.jsonRpc();\n const parser = serialization.makeUnsafe();\n const maxMessageBytes = options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES;\n const configuredHeaders = Headers.fromInput(options.headers);\n const url = options.url;\n let sessionId: string | undefined;\n let protocolVersion: string | undefined;\n let initializeRequestId: string | number | undefined;\n /** Request ids whose JSON-RPC response has been delivered. */\n const answered = new Set<string | number>();\n\n const transportHeaders = (): Headers.Headers =>\n Headers.merge(\n configuredHeaders,\n Headers.fromInput({\n accept: \"application/json, text/event-stream\",\n ...(sessionId === undefined ? {} : { [MCP_SESSION_ID_HEADER]: sessionId }),\n ...(protocolVersion === undefined\n ? {}\n : { [MCP_PROTOCOL_VERSION_HEADER]: protocolVersion }),\n }),\n );\n\n const post = (body: string) =>\n client\n .execute(\n HttpClientRequest.post(url).pipe(\n HttpClientRequest.setHeaders(transportHeaders()),\n HttpClientRequest.bodyText(body, \"application/json\"),\n ),\n )\n .pipe(\n Effect.mapError((error) =>\n protocolDefect(`MCP HTTP request to ${options.serverId} failed`, error),\n ),\n );\n\n // Ending the session is a courtesy to the server; the Scope owns the client.\n yield* Effect.addFinalizer(() =>\n sessionId === undefined\n ? Effect.void\n : client\n .execute(\n HttpClientRequest.delete(url).pipe(HttpClientRequest.setHeaders(transportHeaders())),\n )\n .pipe(Effect.ignore),\n );\n\n return yield* RpcClient.Protocol.make((writeResponse) =>\n Effect.sync(() => {\n const encode = (message: unknown): Effect.Effect<string, RpcClientError.RpcClientError> =>\n Effect.suspend(() => {\n const encoded = parser.encode(mcpWireMessage(message));\n\n return typeof encoded === \"string\"\n ? Effect.succeed(encoded)\n : Effect.fail(protocolDefect(\"Could not encode an MCP JSON-RPC message\"));\n });\n\n const deliver = (clientId: number, data: string): Effect.Effect<void> =>\n Effect.suspend(() => {\n let messages: ReadonlyArray<unknown>;\n\n try {\n messages = parser.decode(data);\n } catch (cause) {\n return writeResponse(clientId, {\n _tag: \"ClientProtocolError\",\n error: protocolDefect(\"Could not decode an MCP JSON-RPC message\", cause),\n });\n }\n\n return Effect.forEach(\n messages,\n (message) =>\n routeMessage(message, {\n clientId,\n writeResponse,\n respond: (response) => encode(response).pipe(Effect.flatMap(post), Effect.ignore),\n onExit: (exit) => {\n answered.add(exit.requestId);\n if (exit.requestId !== initializeRequestId || exit.exit._tag !== \"Success\") {\n return;\n }\n const decoded = decodeInitializeProtocolVersion(exit.exit.value);\n\n if (Option.isSome(decoded)) protocolVersion = decoded.value.protocolVersion;\n },\n }),\n { discard: true },\n );\n });\n\n /**\n * Posts one message and delivers whatever the server answers. A request\n * whose HTTP exchange completes without a JSON-RPC response for its id\n * (for example a `202`, an `id: null` error, or a stream that ends\n * early) fails that request instead of leaving its caller waiting.\n */\n const dispatch = Effect.fn(\"McpHttpTransport.dispatch\")(function* (\n clientId: number,\n message: unknown,\n requestId?: string | number,\n ) {\n const response = yield* post(yield* encode(message));\n const responseSession = response.headers[MCP_SESSION_ID_HEADER];\n\n if (responseSession !== undefined) sessionId = responseSession;\n if (response.status < 200 || response.status >= 300) {\n return yield* protocolDefect(\n `MCP server ${options.serverId} answered HTTP ${response.status}`,\n );\n }\n const contentType = response.headers[\"content-type\"] ?? \"\";\n\n if (response.status !== 202 && response.status !== 204) {\n if (contentType.startsWith(\"text/event-stream\")) {\n yield* consumeEventStream(response, maxMessageBytes, (data) => deliver(clientId, data));\n } else {\n const text = yield* readBoundedText(response, maxMessageBytes);\n\n if (text.length > 0) yield* deliver(clientId, text);\n }\n }\n if (requestId !== undefined && !answered.has(requestId)) {\n yield* writeResponse(clientId, {\n _tag: \"Exit\",\n requestId,\n exit: {\n _tag: \"Failure\",\n cause: [\n {\n _tag: \"Die\",\n defect: `MCP server ${options.serverId} closed the HTTP exchange without answering request ${String(requestId)}`,\n },\n ],\n },\n });\n }\n answered.delete(requestId ?? \"\");\n });\n\n const send: RpcClient.Protocol[\"Service\"][\"send\"] = (clientId, request) => {\n switch (request._tag) {\n case \"Request\": {\n if (isNotificationTag(request.tag)) {\n return dispatch(clientId, { ...request, isNotification: true });\n }\n if (request.tag === \"initialize\") initializeRequestId = request.id;\n\n return dispatch(clientId, request, request.id);\n }\n case \"Interrupt\": {\n return dispatch(clientId, {\n _tag: \"Request\",\n id: request.requestId,\n tag: \"notifications/cancelled\",\n payload: { requestId: request.requestId },\n headers: [],\n isNotification: true,\n } satisfies RpcMessage.RequestEncoded);\n }\n case \"Ack\":\n case \"Ping\":\n case \"Eof\": {\n return Effect.void;\n }\n }\n };\n\n return {\n send,\n supportsAck: false,\n supportsTransferables: false,\n codecFor: serialization.codecFor,\n };\n }),\n );\n});\n\nconst makeStdioProtocol = Effect.fn(\"McpStdioTransport.protocol\")(function* (\n options: McpStdioTransportOptions,\n) {\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n const maxMessageBytes = options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES;\n const serialization = RpcSerialization.ndJsonRpc({ maxBufferSize: maxMessageBytes });\n const parser = serialization.makeUnsafe();\n\n const handle = yield* spawner\n .spawn(\n ChildProcess.make(options.command, [...(options.args ?? [])], {\n ...(options.cwd === undefined ? {} : { cwd: options.cwd }),\n ...(options.env === undefined ? {} : { env: options.env, extendEnv: true }),\n }),\n )\n .pipe(\n Effect.mapError((cause) =>\n McpConnectionError.make({\n serverId: options.serverId,\n message: `Could not start the MCP server process for ${options.serverId}`,\n cause,\n }),\n ),\n );\n\n const outbound = yield* Queue.unbounded<string>();\n // Once the process is gone every later send fails immediately instead of\n // queueing behind a writer that no longer exists.\n let closed: RpcClientError.RpcClientError | undefined;\n\n const closedWith = (message: string, cause?: unknown): RpcClientError.RpcClientError =>\n (closed ??= protocolDefect(message, cause));\n\n yield* Stream.fromQueue(outbound).pipe(\n Stream.encodeText,\n Stream.run(handle.stdin),\n Effect.matchCauseEffect({\n onSuccess: () =>\n Effect.sync(() => closedWith(`MCP server process ${options.serverId} closed stdin`)),\n onFailure: (cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.void\n : Effect.sync(() =>\n closedWith(\n `Writing to MCP server process ${options.serverId} failed`,\n Cause.squash(cause),\n ),\n ),\n }),\n Effect.forkScoped,\n );\n yield* handle.stderr.pipe(\n Stream.decodeText(),\n Stream.splitLines,\n Stream.runForEach((line) => Effect.logDebug(line)),\n Effect.ignore,\n Effect.annotateLogs({ mcpServerId: options.serverId, stream: \"stderr\" }),\n Effect.forkScoped,\n );\n\n return yield* RpcClient.Protocol.make(\n Effect.fnUntraced(function* (writeResponse, clientIds) {\n const broadcast = (error: RpcClientError.RpcClientError) =>\n Effect.forEach(\n clientIds,\n (clientId) => writeResponse(clientId, { _tag: \"ClientProtocolError\", error }),\n { discard: true },\n );\n\n const deliver = (chunk: Uint8Array): Effect.Effect<void> =>\n Effect.suspend(() => {\n let messages: ReadonlyArray<unknown>;\n\n try {\n messages = parser.decode(chunk);\n } catch (cause) {\n return broadcast(protocolDefect(\"Could not decode an MCP stdio frame\", cause));\n }\n\n return Effect.forEach(\n messages,\n (message) =>\n Effect.forEach(\n clientIds,\n (clientId) =>\n routeMessage(message, {\n clientId,\n writeResponse,\n respond: (response) => enqueue(response).pipe(Effect.ignore),\n onExit: () => {},\n }),\n { discard: true },\n ),\n { discard: true },\n );\n });\n\n const enqueue = (message: unknown): Effect.Effect<void, RpcClientError.RpcClientError> =>\n Effect.suspend(() => {\n if (closed !== undefined) return Effect.fail(closed);\n const encoded = parser.encode(mcpWireMessage(message));\n\n if (typeof encoded !== \"string\") {\n return Effect.fail(protocolDefect(\"Could not encode an MCP JSON-RPC message\"));\n }\n\n return Queue.offer(outbound, encoded).pipe(Effect.asVoid);\n });\n\n yield* handle.stdout.pipe(\n Stream.runForEach(deliver),\n Effect.matchCauseEffect({\n onSuccess: () =>\n broadcast(closedWith(`MCP server process ${options.serverId} closed stdout`)),\n onFailure: (cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.void\n : broadcast(\n closedWith(\n `Reading MCP server process ${options.serverId} failed`,\n Cause.squash(cause),\n ),\n ),\n }),\n Effect.forkScoped,\n );\n\n const send: RpcClient.Protocol[\"Service\"][\"send\"] = (_clientId, request) => {\n switch (request._tag) {\n case \"Request\": {\n return enqueue(\n isNotificationTag(request.tag) ? { ...request, isNotification: true } : request,\n );\n }\n case \"Interrupt\": {\n return enqueue({\n _tag: \"Request\",\n id: request.requestId,\n tag: \"notifications/cancelled\",\n payload: { requestId: request.requestId },\n headers: [],\n isNotification: true,\n } satisfies RpcMessage.RequestEncoded);\n }\n case \"Ack\":\n case \"Ping\":\n case \"Eof\": {\n return Effect.void;\n }\n }\n };\n\n return {\n send,\n supportsAck: false,\n supportsTransferables: false,\n codecFor: serialization.codecFor,\n };\n }),\n );\n});\n\n/** Streamable HTTP transport for one remote MCP server; requires `HttpClient`. */\nexport const McpHttpTransport = {\n make: (options: McpHttpTransportOptions): McpServerTransport<HttpClient.HttpClient> => ({\n serverId: options.serverId,\n trustToolAnnotations: options.trustToolAnnotations ?? false,\n protocol: makeHttpProtocol(options),\n }),\n} as const;\n\n/** stdio transport for one local MCP server process; requires `ChildProcessSpawner`. */\nexport const McpStdioTransport = {\n make: (\n options: McpStdioTransportOptions,\n ): McpServerTransport<ChildProcessSpawner.ChildProcessSpawner> => ({\n serverId: options.serverId,\n trustToolAnnotations: options.trustToolAnnotations ?? false,\n protocol: makeStdioProtocol(options),\n }),\n} as const;\n\n/**\n * Effect AI Tool derived from one discovered MCP tool. Its parameters are the\n * server's JSON Schema, so handlers receive `unknown` and the server validates\n * arguments; `Tool.getJsonSchema` still advertises the discovered schema. A\n * failed call returns `McpToolCallFailed` to the model as a failed tool result.\n */\nexport type McpTool = Tool.Tool<\n string,\n {\n readonly parameters: typeof Schema.Unknown;\n readonly success: typeof McpToolResult;\n readonly failure: typeof McpToolCallFailed;\n readonly failureMode: \"return\";\n }\n>;\n\n/** Toolkit of discovered MCP tools; every member forwards `tools/call` to its server. */\nexport type McpToolkit = Toolkit.Toolkit<Record<string, McpTool>>;\n\nconst executionClassFor = (\n annotations: McpSchema.ToolAnnotations | undefined,\n): ToolExecutionClassValue => {\n if (annotations === undefined) return \"uncertain\";\n if (annotations.readOnlyHint) return \"readonly\";\n if (annotations.idempotentHint && !annotations.destructiveHint) return \"idempotent\";\n\n return \"uncertain\";\n};\n\nconst makeMcpTool = (tool: McpSchema.Tool, trustToolAnnotations: boolean): McpTool => {\n // MCP servers may advertise valid JSON Schemas outside a model provider's strict subset.\n let dynamic: McpTool = Tool.dynamic(tool.name, {\n ...(tool.description === undefined ? {} : { description: tool.description }),\n parameters: tool.inputSchema,\n success: McpToolResult,\n failure: McpToolCallFailed,\n // MCP reports tool errors inside results so the model can self-correct;\n // `return` hands the typed failure to the model the same way.\n failureMode: \"return\",\n }).annotate(Tool.Strict, false);\n\n const title = tool.title ?? tool.annotations?.title;\n\n if (title !== undefined) dynamic = dynamic.annotate(Tool.Title, title);\n dynamic = dynamic.annotate(McpToolOutputSchema, Option.fromNullishOr(tool.outputSchema));\n if (tool.annotations !== undefined) {\n dynamic = dynamic\n .annotate(Tool.Readonly, tool.annotations.readOnlyHint)\n .annotate(Tool.Destructive, tool.annotations.destructiveHint)\n .annotate(Tool.Idempotent, tool.annotations.idempotentHint)\n .annotate(Tool.OpenWorld, tool.annotations.openWorldHint);\n }\n if (trustToolAnnotations) {\n dynamic = dynamic.annotate(ToolExecutionClass, executionClassFor(tool.annotations));\n }\n\n return dynamic;\n};\n\nconst ToolArguments = Schema.Record(Schema.String, Schema.Json);\nconst decodeToolArguments = Schema.decodeUnknownEffect(ToolArguments);\n\nconst errorText = (content: ReadonlyArray<typeof McpSchema.ContentBlock.Type>): string =>\n content\n .flatMap((block) => (block.type === \"text\" ? [block.text] : []))\n .join(\"\\n\")\n .slice(0, 4 * 1024);\n\nconst describeDefect = (defect: unknown): string =>\n (Predicate.hasProperty(defect, \"message\") && Predicate.isString(defect.message)\n ? defect.message\n : String(defect)\n ).slice(0, 4 * 1024);\n\nconst connectionError = (serverId: string, message: string) => (cause: unknown) =>\n McpConnectionError.make({ serverId, message, cause });\n\n/**\n * Keeps every non-interrupt outcome of one protocol step typed: expected\n * failures and defects (such as an undecodable server reply) both become the\n * connection error, so a misbehaving server cannot crash the connector.\n */\nconst failClosed =\n (serverId: string, message: string) =>\n <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, McpConnectionError, R> =>\n self.pipe(\n Effect.mapError(connectionError(serverId, message)),\n Effect.catchDefect((defect) => Effect.fail(connectionError(serverId, message)(defect))),\n );\n\nconst connectServer = Effect.fn(\"McpClient.connect\")(function* <R>(\n transport: McpServerTransport<R>,\n request: McpConnectionRequest,\n clientInfo: McpSchema.Implementation,\n): Effect.fn.Return<McpConnectedServer, McpConnectionError, Scope.Scope | R> {\n const serverId = transport.serverId;\n const protocol = yield* transport.protocol;\n\n const client = yield* RpcClient.make(McpSchema.ClientRpcs, {\n spanPrefix: \"McpClient\",\n spanAttributes: { \"mcp.server_id\": serverId },\n }).pipe(Effect.provideService(RpcClient.Protocol, protocol));\n\n const initialized = yield* client\n .initialize({\n protocolVersion: OFFERED_PROTOCOL_VERSION,\n capabilities: McpSchema.ClientCapabilities.make({}),\n clientInfo,\n })\n .pipe(failClosed(serverId, `MCP initialize with ${serverId} failed`));\n\n const negotiated = yield* Schema.decodeUnknownEffect(McpClientProtocolVersion)(\n initialized.protocolVersion,\n ).pipe(\n Effect.mapError(\n connectionError(\n serverId,\n `MCP server ${serverId} negotiated unsupported protocol version '${initialized.protocolVersion}'`,\n ),\n ),\n );\n\n yield* Effect.annotateCurrentSpan({ \"mcp.protocol_version\": negotiated });\n yield* client[\"notifications/initialized\"](undefined, { discard: true }).pipe(\n failClosed(serverId, `Could not acknowledge MCP initialization with ${serverId}`),\n );\n\n const tools: Array<McpSchema.Tool> = [];\n let cursor: string | undefined;\n let pages = 0;\n\n do {\n const page = yield* client[\"tools/list\"](\n cursor === undefined ? undefined : McpSchema.PaginatedRequestMeta.make({ cursor }),\n ).pipe(failClosed(serverId, `MCP tools/list with ${serverId} failed`));\n\n tools.push(...page.tools);\n cursor = page.nextCursor;\n pages += 1;\n // `validateMcpDiscovery` rejects the count; stop paying for more pages.\n if (tools.length > request.maxToolCount) break;\n if (cursor !== undefined && pages >= MAX_TOOL_LIST_PAGES) {\n return yield* McpConnectionError.make({\n serverId,\n message: `MCP server ${serverId} paginated tools/list beyond ${MAX_TOOL_LIST_PAGES} pages`,\n });\n }\n } while (cursor !== undefined);\n\n const callTool = Effect.fn(\"McpClient.callTool\")(function* (name: string, params: unknown) {\n const args = yield* decodeToolArguments(params ?? {}).pipe(\n Effect.mapError((cause) =>\n McpToolCallFailed.make({\n serverId,\n tool: name,\n reason: \"invalid-arguments\",\n message: `MCP tool arguments must be a JSON object: ${cause.message}`,\n }),\n ),\n );\n\n const result = yield* client[\"tools/call\"]({ name, arguments: args }).pipe(\n Effect.mapError((error) =>\n McpToolCallFailed.make({\n serverId,\n tool: name,\n reason: isRpcClientError(error) ? \"transport\" : \"protocol-error\",\n message: error.message,\n }),\n ),\n // A JSON-RPC error the MCP error union cannot decode (or any other\n // malformed reply) surfaces as a defect from the RPC client. It is still\n // the server's answer, so it reaches the model as a failed tool result\n // rather than aborting the batch.\n Effect.catchDefect((defect) =>\n Effect.fail(\n McpToolCallFailed.make({\n serverId,\n tool: name,\n reason: \"protocol-error\",\n message: describeDefect(defect),\n }),\n ),\n ),\n );\n\n if (result.isError === true) {\n return yield* McpToolCallFailed.make({\n serverId,\n tool: name,\n reason: \"tool-error\",\n message: errorText(result.content),\n content: result.content,\n });\n }\n\n return McpToolResult.make({\n content: result.content,\n ...(result.structuredContent === undefined\n ? {}\n : { structuredContent: result.structuredContent }),\n });\n });\n\n const toolkit: McpToolkit = yield* Effect.try({\n try: () =>\n Toolkit.make(...tools.map((tool) => makeMcpTool(tool, transport.trustToolAnnotations))),\n catch: connectionError(\n serverId,\n `MCP server ${serverId} advertised tools that cannot form a Toolkit`,\n ),\n });\n\n const handlers = toolkit.toLayer(\n Object.fromEntries(\n tools.map((tool) => [tool.name, (params: unknown) => callTool(tool.name, params)] as const),\n ),\n );\n\n return {\n identity: McpServerIdentity.make({ serverId, implementation: initialized.serverInfo }),\n capabilities: initialized.capabilities,\n tools,\n toolkit,\n handlers,\n } satisfies McpConnectedServer;\n});\n\n/** Platform services one transport needs, as declared by `McpServerTransport<R>`. */\nexport type McpTransportRequirements<Transport> =\n Transport extends McpServerTransport<infer R> ? R : never;\n\nconst makeConnectorLayer = <R>(\n transports: ReadonlyArray<McpServerTransport<R>>,\n options: { readonly clientInfo?: McpSchema.Implementation | undefined } | undefined,\n): Layer.Layer<McpConnector, never, R> =>\n Layer.effect(McpConnector)(\n Effect.gen(function* () {\n const services = yield* Effect.context<R>();\n const byServerId = new Map(transports.map((transport) => [transport.serverId, transport]));\n const clientInfo = options?.clientInfo ?? defaultMcpClientInfo;\n\n return McpConnector.of({\n connect: (request) => {\n const transport = byServerId.get(request.serverId);\n\n if (transport === undefined) {\n return Effect.fail(\n McpConnectionError.make({\n serverId: request.serverId,\n message: `No MCP transport is configured for server '${request.serverId}'`,\n }),\n );\n }\n\n // The Layer supplies the transport's platform services, but the\n // connection must live and die with the caller's Scope, never the\n // Layer's.\n return connectServer(transport, request, clientInfo).pipe(\n Effect.updateContext((caller: Context.Context<Scope.Scope>) =>\n Context.merge(Context.merge(caller, services), Context.pick(Scope.Scope)(caller)),\n ),\n );\n },\n });\n }),\n );\n\n/**\n * `McpConnector` over real transports. Each `connect` acquires the transport\n * in the caller's Scope, negotiates a protocol revision, lists tools within the\n * request bounds, and returns dynamic Effect AI Tools plus the handler Layer\n * that forwards their calls. The Layer requires the union of every\n * transport's platform services.\n */\nexport const layer = <const Transports extends ReadonlyArray<McpServerTransport<unknown>>>(\n transports: Transports,\n options?: { readonly clientInfo?: McpSchema.Implementation | undefined },\n): Layer.Layer<McpConnector, never, McpTransportRequirements<Transports[number]>> =>\n makeConnectorLayer(\n // Type-level only: each element declares its own `R`, and the Layer\n // requires their union. Nothing about the values changes.\n transports as ReadonlyArray<McpServerTransport<McpTransportRequirements<Transports[number]>>>,\n options,\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAM,4BAA4B;;AAElC,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAC9B,MAAM,8BAA8B;AACpC,MAAM,4BAA4B;;;;;;AAOlC,MAAa,2BAA2B,OAAO,SAAS;CACtD,YAAY,YAAY;CACxB,YAAY,YAAY;CACxB,YAAY,YAAY;CACxB,YAAY,YAAY;AAC1B,CAAC;AAID,MAAM,2BAAqD,YAAY,YAAY;;AAGnF,MAAa,uBAAuB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AQ,QAAQ,GAAG,QAAQ,KAAK,MAAM,KAAK,CAAC,CAAC,MAAM,CAAC,CAClF,CACF;CACF,EACF,CAAC;AACH,CAAC,CACH;;;;;;;;AASF,MAAa,SACX,YACA,YAEA,mBAGE,YACA,OACF"}
|
|
@@ -616,25 +616,6 @@ export declare const readPending: (request: Pick<{
|
|
|
616
616
|
readonly reportKind?: "update" | undefined;
|
|
617
617
|
} | undefined;
|
|
618
618
|
readonly messageAdmission?: {
|
|
619
|
-
readonly schemaVersion: 1;
|
|
620
|
-
readonly message: {
|
|
621
|
-
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
622
|
-
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
623
|
-
};
|
|
624
|
-
readonly peerName: string;
|
|
625
|
-
readonly sender: {
|
|
626
|
-
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
627
|
-
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
628
|
-
};
|
|
629
|
-
readonly returnAddress: {
|
|
630
|
-
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
631
|
-
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
632
|
-
};
|
|
633
|
-
readonly inReplyTo?: {
|
|
634
|
-
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
635
|
-
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
636
|
-
} | undefined;
|
|
637
|
-
} | {
|
|
638
619
|
readonly _tag: "WorkerCompletion";
|
|
639
620
|
readonly budgetExhausted: boolean;
|
|
640
621
|
readonly schemaVersion: 1;
|
|
@@ -675,6 +656,25 @@ export declare const readPending: (request: Pick<{
|
|
|
675
656
|
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
676
657
|
};
|
|
677
658
|
readonly update: Update;
|
|
659
|
+
} | {
|
|
660
|
+
readonly schemaVersion: 1;
|
|
661
|
+
readonly message: {
|
|
662
|
+
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
663
|
+
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
664
|
+
};
|
|
665
|
+
readonly peerName: string;
|
|
666
|
+
readonly sender: {
|
|
667
|
+
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
668
|
+
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
669
|
+
};
|
|
670
|
+
readonly returnAddress: {
|
|
671
|
+
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
672
|
+
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
673
|
+
};
|
|
674
|
+
readonly inReplyTo?: {
|
|
675
|
+
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
676
|
+
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
677
|
+
} | undefined;
|
|
678
678
|
} | undefined;
|
|
679
679
|
};
|
|
680
680
|
readonly envelopeDigest: string & import("effect/Brand").Brand<"@effect-agent/thread/Digest">;
|
|
@@ -817,25 +817,6 @@ export declare const prepareMessageDelivery: (options: {
|
|
|
817
817
|
readonly reportKind?: "update" | undefined;
|
|
818
818
|
} | undefined;
|
|
819
819
|
readonly messageAdmission?: {
|
|
820
|
-
readonly schemaVersion: 1;
|
|
821
|
-
readonly message: {
|
|
822
|
-
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
823
|
-
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
824
|
-
};
|
|
825
|
-
readonly peerName: string;
|
|
826
|
-
readonly sender: {
|
|
827
|
-
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
828
|
-
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
829
|
-
};
|
|
830
|
-
readonly returnAddress: {
|
|
831
|
-
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
832
|
-
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
833
|
-
};
|
|
834
|
-
readonly inReplyTo?: {
|
|
835
|
-
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
836
|
-
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
837
|
-
} | undefined;
|
|
838
|
-
} | {
|
|
839
820
|
readonly _tag: "WorkerCompletion";
|
|
840
821
|
readonly budgetExhausted: boolean;
|
|
841
822
|
readonly schemaVersion: 1;
|
|
@@ -876,6 +857,25 @@ export declare const prepareMessageDelivery: (options: {
|
|
|
876
857
|
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
877
858
|
};
|
|
878
859
|
readonly update: Update;
|
|
860
|
+
} | {
|
|
861
|
+
readonly schemaVersion: 1;
|
|
862
|
+
readonly message: {
|
|
863
|
+
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
864
|
+
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
865
|
+
};
|
|
866
|
+
readonly peerName: string;
|
|
867
|
+
readonly sender: {
|
|
868
|
+
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
869
|
+
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
870
|
+
};
|
|
871
|
+
readonly returnAddress: {
|
|
872
|
+
readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
873
|
+
readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
|
|
874
|
+
};
|
|
875
|
+
readonly inReplyTo?: {
|
|
876
|
+
readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
|
|
877
|
+
readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
|
|
878
|
+
} | undefined;
|
|
879
879
|
} | undefined;
|
|
880
880
|
};
|
|
881
881
|
readonly envelopeDigest: string & import("effect/Brand").Brand<"@effect-agent/thread/Digest">;
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"effect-agent","version":"0.1.0-beta.136","devDependencies":{"@effect/platform-node":"4.0.0-rc.117","@effect/vitest":"4.0.0-rc.117","effect":"4.0.0-rc.117","typescript":"7.0.2","vite-plus":"0.3.2"},"peerDependencies":{"effect":"^4.0.0-rc.117"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./activity-store":{"types":"./dist/durable/ActivityStore.d.mts","default":"./dist/durable/ActivityStore.mjs"},"./admin":{"types":"./dist/durable/Admin.d.mts","default":"./dist/durable/Admin.mjs"},"./agent":{"types":"./dist/core/Agent.d.mts","default":"./dist/core/Agent.mjs"},"./agent-error":{"types":"./dist/core/AgentError.d.mts","default":"./dist/core/AgentError.mjs"},"./agent-policy":{"types":"./dist/core/AgentPolicy.d.mts","default":"./dist/core/AgentPolicy.mjs"},"./agent-registration":{"types":"./dist/durable/AgentRegistration.d.mts","default":"./dist/durable/AgentRegistration.mjs"},"./agent-runtime":{"types":"./dist/engine/AgentRuntime.d.mts","default":"./dist/engine/AgentRuntime.mjs"},"./agent-updates":{"types":"./dist/core/AgentUpdates.d.mts","default":"./dist/core/AgentUpdates.mjs"},"./approval":{"types":"./dist/capabilities/Approval.d.mts","default":"./dist/capabilities/Approval.mjs"},"./budget":{"types":"./dist/capabilities/Budget.d.mts","default":"./dist/capabilities/Budget.mjs"},"./code-executor":{"types":"./dist/sandbox/CodeExecutor.d.mts","default":"./dist/sandbox/CodeExecutor.mjs"},"./code-mode":{"types":"./dist/capabilities/CodeMode.d.mts","default":"./dist/capabilities/CodeMode.mjs"},"./commands":{"types":"./dist/capabilities/Commands.d.mts","default":"./dist/capabilities/Commands.mjs"},"./committed-activity":{"types":"./dist/durable/CommittedActivity.d.mts","default":"./dist/durable/CommittedActivity.mjs"},"./compaction":{"types":"./dist/engine/Compaction.d.mts","default":"./dist/engine/Compaction.mjs"},"./context-compactor":{"types":"./dist/engine/ContextCompactor.d.mts","default":"./dist/engine/ContextCompactor.mjs"},"./context-history":{"types":"./dist/engine/ContextHistory.d.mts","default":"./dist/engine/ContextHistory.mjs"},"./context-tools":{"types":"./dist/capabilities/ContextTools.d.mts","default":"./dist/capabilities/ContextTools.mjs"},"./context-window":{"types":"./dist/engine/ContextWindow.d.mts","default":"./dist/engine/ContextWindow.mjs"},"./digest":{"types":"./dist/durable/Digest.d.mts","default":"./dist/durable/Digest.mjs"},"./durable-agent-runtime":{"types":"./dist/durable/DurableAgentRuntime.d.mts","default":"./dist/durable/DurableAgentRuntime.mjs"},"./durable-failpoint":{"types":"./dist/durable/DurableFailpoint.d.mts","default":"./dist/durable/DurableFailpoint.mjs"},"./durable-step":{"types":"./dist/engine/DurableStep.d.mts","default":"./dist/engine/DurableStep.mjs"},"./event-source":{"types":"./dist/durable/EventSource.d.mts","default":"./dist/durable/EventSource.mjs"},"./failure-diagnostic":{"types":"./dist/core/FailureDiagnostic.d.mts","default":"./dist/core/FailureDiagnostic.mjs"},"./git-hub-workflow-source":{"types":"./dist/durable/GitHubWorkflowSource.d.mts","default":"./dist/durable/GitHubWorkflowSource.mjs"},"./id-generator":{"types":"./dist/core/IdGenerator.d.mts","default":"./dist/core/IdGenerator.mjs"},"./identifiers":{"types":"./dist/core/Identifiers.d.mts","default":"./dist/core/Identifiers.mjs"},"./in-memory":{"types":"./dist/InMemory.d.mts","default":"./dist/InMemory.mjs"},"./interactive-browser":{"types":"./dist/sandbox/InteractiveBrowser.d.mts","default":"./dist/sandbox/InteractiveBrowser.mjs"},"./mcp":{"types":"./dist/capabilities/Mcp.d.mts","default":"./dist/capabilities/Mcp.mjs"},"./mcp-client":{"types":"./dist/capabilities/McpClient.d.mts","default":"./dist/capabilities/McpClient.mjs"},"./memory":{"types":"./dist/core/Memory.d.mts","default":"./dist/core/Memory.mjs"},"./memory-namespace":{"types":"./dist/core/MemoryNamespace.d.mts","default":"./dist/core/MemoryNamespace.mjs"},"./memory-notes":{"types":"./dist/capabilities/MemoryNotes.d.mts","default":"./dist/capabilities/MemoryNotes.mjs"},"./memory-reference":{"types":"./dist/core/MemoryReference.d.mts","default":"./dist/core/MemoryReference.mjs"},"./memory-revalidation":{"types":"./dist/core/MemoryRevalidation.d.mts","default":"./dist/core/MemoryRevalidation.mjs"},"./memory-store":{"types":"./dist/core/MemoryStore.d.mts","default":"./dist/core/MemoryStore.mjs"},"./message-delivery":{"types":"./dist/durable/MessageDelivery.d.mts","default":"./dist/durable/MessageDelivery.mjs"},"./messaging":{"types":"./dist/capabilities/Messaging.d.mts","default":"./dist/capabilities/Messaging.mjs"},"./messaging-host":{"types":"./dist/engine/MessagingHost.d.mts","default":"./dist/engine/MessagingHost.mjs"},"./model-context":{"types":"./dist/capabilities/ModelContext.d.mts","default":"./dist/capabilities/ModelContext.mjs"},"./operation-authorizer":{"types":"./dist/durable/OperationAuthorizer.d.mts","default":"./dist/durable/OperationAuthorizer.mjs"},"./output":{"types":"./dist/engine/Output.d.mts","default":"./dist/engine/Output.mjs"},"./page-capture":{"types":"./dist/sandbox/PageCapture.d.mts","default":"./dist/sandbox/PageCapture.mjs"},"./page-crawl":{"types":"./dist/sandbox/PageCrawl.d.mts","default":"./dist/sandbox/PageCrawl.mjs"},"./page-screenshot":{"types":"./dist/sandbox/PageScreenshot.d.mts","default":"./dist/sandbox/PageScreenshot.mjs"},"./persistent-history":{"types":"./dist/durable/PersistentHistory.d.mts","default":"./dist/durable/PersistentHistory.mjs"},"./prepared-input-admission":{"types":"./dist/durable/PreparedInputAdmission.d.mts","default":"./dist/durable/PreparedInputAdmission.mjs"},"./receipt":{"types":"./dist/core/Receipt.d.mts","default":"./dist/core/Receipt.mjs"},"./records":{"types":"./dist/durable/Records.d.mts","default":"./dist/durable/Records.mjs"},"./recovery":{"types":"./dist/durable/Recovery.d.mts","default":"./dist/durable/Recovery.mjs"},"./redaction":{"types":"./dist/capabilities/Redaction.d.mts","default":"./dist/capabilities/Redaction.mjs"},"./remembering":{"types":"./dist/capabilities/Remembering.d.mts","default":"./dist/capabilities/Remembering.mjs"},"./remembering-store":{"types":"./dist/core/RememberingStore.d.mts","default":"./dist/core/RememberingStore.mjs"},"./run-event":{"types":"./dist/core/RunEvent.d.mts","default":"./dist/core/RunEvent.mjs"},"./run-event-sink":{"types":"./dist/engine/RunEventSink.d.mts","default":"./dist/engine/RunEventSink.mjs"},"./run-hooks":{"types":"./dist/capabilities/RunHooks.d.mts","default":"./dist/capabilities/RunHooks.mjs"},"./run-journal":{"types":"./dist/durable/RunJournal.d.mts","default":"./dist/durable/RunJournal.mjs"},"./run-options":{"types":"./dist/engine/RunOptions.d.mts","default":"./dist/engine/RunOptions.mjs"},"./run-policy-usage":{"types":"./dist/core/RunPolicyUsage.d.mts","default":"./dist/core/RunPolicyUsage.mjs"},"./sandbox":{"types":"./dist/sandbox/Sandbox.d.mts","default":"./dist/sandbox/Sandbox.mjs"},"./schedule":{"types":"./dist/durable/Schedule.d.mts","default":"./dist/durable/Schedule.mjs"},"./schedule-transition":{"types":"./dist/durable/ScheduleTransition.d.mts","default":"./dist/durable/ScheduleTransition.mjs"},"./scheduling":{"types":"./dist/durable/Scheduling.d.mts","default":"./dist/durable/Scheduling.mjs"},"./semantic-memory":{"types":"./dist/capabilities/SemanticMemory.d.mts","default":"./dist/capabilities/SemanticMemory.mjs"},"./semantic-memory-index":{"types":"./dist/core/SemanticMemoryIndex.d.mts","default":"./dist/core/SemanticMemoryIndex.mjs"},"./semantic-memory-revalidation":{"types":"./dist/core/SemanticMemoryRevalidation.d.mts","default":"./dist/core/SemanticMemoryRevalidation.mjs"},"./sql-thread-native-reads":{"types":"./dist/durable/SqlThreadNativeReads.d.mts","default":"./dist/durable/SqlThreadNativeReads.mjs"},"./sql-memory-store":{"types":"./dist/durable/SqlMemoryStore.d.mts","default":"./dist/durable/SqlMemoryStore.mjs"},"./sql-message-delivery-store":{"types":"./dist/durable/SqlMessageDeliveryStore.d.mts","default":"./dist/durable/SqlMessageDeliveryStore.mjs"},"./sql-storage-v2-upgrade":{"types":"./dist/durable/SqlStorageV2Upgrade.d.mts","default":"./dist/durable/SqlStorageV2Upgrade.mjs"},"./sql-subscription-store":{"types":"./dist/durable/SqlSubscriptionStore.d.mts","default":"./dist/durable/SqlSubscriptionStore.mjs"},"./subagent":{"types":"./dist/capabilities/Subagent.d.mts","default":"./dist/capabilities/Subagent.mjs"},"./subagent-contract":{"types":"./dist/core/SubagentContract.d.mts","default":"./dist/core/SubagentContract.mjs"},"./subagent-host":{"types":"./dist/engine/SubagentHost.d.mts","default":"./dist/engine/SubagentHost.mjs"},"./subagent-reservations":{"types":"./dist/capabilities/SubagentReservations.d.mts","default":"./dist/capabilities/SubagentReservations.mjs"},"./submission-ledger":{"types":"./dist/durable/SubmissionLedger.d.mts","default":"./dist/durable/SubmissionLedger.mjs"},"./submission-status":{"types":"./dist/durable/SubmissionStatus.d.mts","default":"./dist/durable/SubmissionStatus.mjs"},"./subscription":{"types":"./dist/durable/Subscription.d.mts","default":"./dist/durable/Subscription.mjs"},"./subscription-input":{"types":"./dist/durable/SubscriptionInput.d.mts","default":"./dist/durable/SubscriptionInput.mjs"},"./subscription-tools":{"types":"./dist/durable/SubscriptionTools.d.mts","default":"./dist/durable/SubscriptionTools.mjs"},"./subscription-transition":{"types":"./dist/durable/SubscriptionTransition.d.mts","default":"./dist/durable/SubscriptionTransition.mjs"},"./subscriptions":{"types":"./dist/durable/Subscriptions.d.mts","default":"./dist/durable/Subscriptions.mjs"},"./testing/certification":{"types":"./dist/durable/Certification.d.mts","default":"./dist/durable/Certification.mjs"},"./testing/durable-failpoint-test-control":{"types":"./dist/durable/DurableFailpointTestControl.d.mts","default":"./dist/durable/DurableFailpointTestControl.mjs"},"./testing/message-delivery-store-conformance":{"types":"./dist/durable/MessageDeliveryStoreConformance.d.mts","default":"./dist/durable/MessageDeliveryStoreConformance.mjs"},"./testing/schedule-store-conformance":{"types":"./dist/durable/ScheduleStoreConformance.d.mts","default":"./dist/durable/ScheduleStoreConformance.mjs"},"./testing/submission-ledger-conformance":{"types":"./dist/durable/SubmissionLedgerConformance.d.mts","default":"./dist/durable/SubmissionLedgerConformance.mjs"},"./testing/subscription-store-conformance":{"types":"./dist/durable/SubscriptionStoreConformance.d.mts","default":"./dist/durable/SubscriptionStoreConformance.mjs"},"./testing/thread-store-conformance":{"types":"./dist/durable/ThreadStoreConformance.d.mts","default":"./dist/durable/ThreadStoreConformance.mjs"},"./thread":{"types":"./dist/core/Thread.d.mts","default":"./dist/core/Thread.mjs"},"./thread-context-history":{"types":"./dist/durable/ThreadContextHistory.d.mts","default":"./dist/durable/ThreadContextHistory.mjs"},"./thread-context-history-projection":{"types":"./dist/durable/ThreadContextHistoryProjection.d.mts","default":"./dist/durable/ThreadContextHistoryProjection.mjs"},"./thread-history":{"types":"./dist/engine/ThreadHistory.d.mts","default":"./dist/engine/ThreadHistory.mjs"},"./thread-invariants":{"types":"./dist/durable/ThreadInvariants.d.mts","default":"./dist/durable/ThreadInvariants.mjs"},"./thread-projection":{"types":"./dist/durable/ThreadProjection.d.mts","default":"./dist/durable/ThreadProjection.mjs"},"./thread-projection-maintenance":{"types":"./dist/durable/ThreadProjectionMaintenance.d.mts","default":"./dist/durable/ThreadProjectionMaintenance.mjs"},"./thread-store":{"types":"./dist/durable/ThreadStore.d.mts","default":"./dist/durable/ThreadStore.mjs"},"./tool-broker":{"types":"./dist/engine/ToolBroker.d.mts","default":"./dist/engine/ToolBroker.mjs"},"./tool-discovery":{"types":"./dist/capabilities/ToolDiscovery.d.mts","default":"./dist/capabilities/ToolDiscovery.mjs"},"./tool-exposure":{"types":"./dist/ToolExposure.d.mts","default":"./dist/ToolExposure.mjs"},"./tool-reconciler":{"types":"./dist/durable/ToolReconciler.d.mts","default":"./dist/durable/ToolReconciler.mjs"},"./tool-result":{"types":"./dist/core/ToolResult.d.mts","default":"./dist/core/ToolResult.mjs"},"./usage":{"types":"./dist/core/Usage.d.mts","default":"./dist/core/Usage.mjs"},"./wake-scheduler":{"types":"./dist/durable/WakeScheduler.d.mts","default":"./dist/durable/WakeScheduler.mjs"},"./web-capture":{"types":"./dist/capabilities/WebCapture.d.mts","default":"./dist/capabilities/WebCapture.mjs"},"./web-search":{"types":"./dist/capabilities/WebSearch.d.mts","default":"./dist/capabilities/WebSearch.mjs"},"./worker":{"types":"./dist/core/Worker.d.mts","default":"./dist/core/Worker.mjs"},"./worker-host":{"types":"./dist/durable/WorkerHost.d.mts","default":"./dist/durable/WorkerHost.mjs"}},"description":"Effect-native agents, execution, subagents, and sandbox contracts in one tree-shakeable package.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/danieljvdm/effect-agent.git","directory":"packages/effect-agent"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json","test":"vp test --passWithNoTests"}}
|
|
1
|
+
{"name":"effect-agent","version":"0.1.0-beta.138","devDependencies":{"@effect/platform-node":"4.0.0-rc.117","@effect/vitest":"4.0.0-rc.117","effect":"4.0.0-rc.117","typescript":"7.0.2","vite-plus":"0.3.2"},"peerDependencies":{"effect":"^4.0.0-rc.117"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./activity-store":{"types":"./dist/durable/ActivityStore.d.mts","default":"./dist/durable/ActivityStore.mjs"},"./admin":{"types":"./dist/durable/Admin.d.mts","default":"./dist/durable/Admin.mjs"},"./agent":{"types":"./dist/core/Agent.d.mts","default":"./dist/core/Agent.mjs"},"./agent-error":{"types":"./dist/core/AgentError.d.mts","default":"./dist/core/AgentError.mjs"},"./agent-policy":{"types":"./dist/core/AgentPolicy.d.mts","default":"./dist/core/AgentPolicy.mjs"},"./agent-registration":{"types":"./dist/durable/AgentRegistration.d.mts","default":"./dist/durable/AgentRegistration.mjs"},"./agent-runtime":{"types":"./dist/engine/AgentRuntime.d.mts","default":"./dist/engine/AgentRuntime.mjs"},"./agent-updates":{"types":"./dist/core/AgentUpdates.d.mts","default":"./dist/core/AgentUpdates.mjs"},"./approval":{"types":"./dist/capabilities/Approval.d.mts","default":"./dist/capabilities/Approval.mjs"},"./budget":{"types":"./dist/capabilities/Budget.d.mts","default":"./dist/capabilities/Budget.mjs"},"./code-executor":{"types":"./dist/sandbox/CodeExecutor.d.mts","default":"./dist/sandbox/CodeExecutor.mjs"},"./code-mode":{"types":"./dist/capabilities/CodeMode.d.mts","default":"./dist/capabilities/CodeMode.mjs"},"./commands":{"types":"./dist/capabilities/Commands.d.mts","default":"./dist/capabilities/Commands.mjs"},"./committed-activity":{"types":"./dist/durable/CommittedActivity.d.mts","default":"./dist/durable/CommittedActivity.mjs"},"./compaction":{"types":"./dist/engine/Compaction.d.mts","default":"./dist/engine/Compaction.mjs"},"./context-compactor":{"types":"./dist/engine/ContextCompactor.d.mts","default":"./dist/engine/ContextCompactor.mjs"},"./context-history":{"types":"./dist/engine/ContextHistory.d.mts","default":"./dist/engine/ContextHistory.mjs"},"./context-tools":{"types":"./dist/capabilities/ContextTools.d.mts","default":"./dist/capabilities/ContextTools.mjs"},"./context-window":{"types":"./dist/engine/ContextWindow.d.mts","default":"./dist/engine/ContextWindow.mjs"},"./digest":{"types":"./dist/durable/Digest.d.mts","default":"./dist/durable/Digest.mjs"},"./durable-agent-runtime":{"types":"./dist/durable/DurableAgentRuntime.d.mts","default":"./dist/durable/DurableAgentRuntime.mjs"},"./durable-failpoint":{"types":"./dist/durable/DurableFailpoint.d.mts","default":"./dist/durable/DurableFailpoint.mjs"},"./durable-step":{"types":"./dist/engine/DurableStep.d.mts","default":"./dist/engine/DurableStep.mjs"},"./event-source":{"types":"./dist/durable/EventSource.d.mts","default":"./dist/durable/EventSource.mjs"},"./failure-diagnostic":{"types":"./dist/core/FailureDiagnostic.d.mts","default":"./dist/core/FailureDiagnostic.mjs"},"./git-hub-workflow-source":{"types":"./dist/durable/GitHubWorkflowSource.d.mts","default":"./dist/durable/GitHubWorkflowSource.mjs"},"./id-generator":{"types":"./dist/core/IdGenerator.d.mts","default":"./dist/core/IdGenerator.mjs"},"./identifiers":{"types":"./dist/core/Identifiers.d.mts","default":"./dist/core/Identifiers.mjs"},"./in-memory":{"types":"./dist/InMemory.d.mts","default":"./dist/InMemory.mjs"},"./interactive-browser":{"types":"./dist/sandbox/InteractiveBrowser.d.mts","default":"./dist/sandbox/InteractiveBrowser.mjs"},"./mcp":{"types":"./dist/capabilities/Mcp.d.mts","default":"./dist/capabilities/Mcp.mjs"},"./mcp-client":{"types":"./dist/capabilities/McpClient.d.mts","default":"./dist/capabilities/McpClient.mjs"},"./memory":{"types":"./dist/core/Memory.d.mts","default":"./dist/core/Memory.mjs"},"./memory-namespace":{"types":"./dist/core/MemoryNamespace.d.mts","default":"./dist/core/MemoryNamespace.mjs"},"./memory-notes":{"types":"./dist/capabilities/MemoryNotes.d.mts","default":"./dist/capabilities/MemoryNotes.mjs"},"./memory-reference":{"types":"./dist/core/MemoryReference.d.mts","default":"./dist/core/MemoryReference.mjs"},"./memory-revalidation":{"types":"./dist/core/MemoryRevalidation.d.mts","default":"./dist/core/MemoryRevalidation.mjs"},"./memory-store":{"types":"./dist/core/MemoryStore.d.mts","default":"./dist/core/MemoryStore.mjs"},"./message-delivery":{"types":"./dist/durable/MessageDelivery.d.mts","default":"./dist/durable/MessageDelivery.mjs"},"./messaging":{"types":"./dist/capabilities/Messaging.d.mts","default":"./dist/capabilities/Messaging.mjs"},"./messaging-host":{"types":"./dist/engine/MessagingHost.d.mts","default":"./dist/engine/MessagingHost.mjs"},"./model-context":{"types":"./dist/capabilities/ModelContext.d.mts","default":"./dist/capabilities/ModelContext.mjs"},"./operation-authorizer":{"types":"./dist/durable/OperationAuthorizer.d.mts","default":"./dist/durable/OperationAuthorizer.mjs"},"./output":{"types":"./dist/engine/Output.d.mts","default":"./dist/engine/Output.mjs"},"./page-capture":{"types":"./dist/sandbox/PageCapture.d.mts","default":"./dist/sandbox/PageCapture.mjs"},"./page-crawl":{"types":"./dist/sandbox/PageCrawl.d.mts","default":"./dist/sandbox/PageCrawl.mjs"},"./page-screenshot":{"types":"./dist/sandbox/PageScreenshot.d.mts","default":"./dist/sandbox/PageScreenshot.mjs"},"./persistent-history":{"types":"./dist/durable/PersistentHistory.d.mts","default":"./dist/durable/PersistentHistory.mjs"},"./prepared-input-admission":{"types":"./dist/durable/PreparedInputAdmission.d.mts","default":"./dist/durable/PreparedInputAdmission.mjs"},"./receipt":{"types":"./dist/core/Receipt.d.mts","default":"./dist/core/Receipt.mjs"},"./records":{"types":"./dist/durable/Records.d.mts","default":"./dist/durable/Records.mjs"},"./recovery":{"types":"./dist/durable/Recovery.d.mts","default":"./dist/durable/Recovery.mjs"},"./redaction":{"types":"./dist/capabilities/Redaction.d.mts","default":"./dist/capabilities/Redaction.mjs"},"./remembering":{"types":"./dist/capabilities/Remembering.d.mts","default":"./dist/capabilities/Remembering.mjs"},"./remembering-store":{"types":"./dist/core/RememberingStore.d.mts","default":"./dist/core/RememberingStore.mjs"},"./run-event":{"types":"./dist/core/RunEvent.d.mts","default":"./dist/core/RunEvent.mjs"},"./run-event-sink":{"types":"./dist/engine/RunEventSink.d.mts","default":"./dist/engine/RunEventSink.mjs"},"./run-hooks":{"types":"./dist/capabilities/RunHooks.d.mts","default":"./dist/capabilities/RunHooks.mjs"},"./run-journal":{"types":"./dist/durable/RunJournal.d.mts","default":"./dist/durable/RunJournal.mjs"},"./run-options":{"types":"./dist/engine/RunOptions.d.mts","default":"./dist/engine/RunOptions.mjs"},"./run-policy-usage":{"types":"./dist/core/RunPolicyUsage.d.mts","default":"./dist/core/RunPolicyUsage.mjs"},"./sandbox":{"types":"./dist/sandbox/Sandbox.d.mts","default":"./dist/sandbox/Sandbox.mjs"},"./schedule":{"types":"./dist/durable/Schedule.d.mts","default":"./dist/durable/Schedule.mjs"},"./schedule-transition":{"types":"./dist/durable/ScheduleTransition.d.mts","default":"./dist/durable/ScheduleTransition.mjs"},"./scheduling":{"types":"./dist/durable/Scheduling.d.mts","default":"./dist/durable/Scheduling.mjs"},"./semantic-memory":{"types":"./dist/capabilities/SemanticMemory.d.mts","default":"./dist/capabilities/SemanticMemory.mjs"},"./semantic-memory-index":{"types":"./dist/core/SemanticMemoryIndex.d.mts","default":"./dist/core/SemanticMemoryIndex.mjs"},"./semantic-memory-revalidation":{"types":"./dist/core/SemanticMemoryRevalidation.d.mts","default":"./dist/core/SemanticMemoryRevalidation.mjs"},"./sql-thread-native-reads":{"types":"./dist/durable/SqlThreadNativeReads.d.mts","default":"./dist/durable/SqlThreadNativeReads.mjs"},"./sql-memory-store":{"types":"./dist/durable/SqlMemoryStore.d.mts","default":"./dist/durable/SqlMemoryStore.mjs"},"./sql-message-delivery-store":{"types":"./dist/durable/SqlMessageDeliveryStore.d.mts","default":"./dist/durable/SqlMessageDeliveryStore.mjs"},"./sql-storage-v2-upgrade":{"types":"./dist/durable/SqlStorageV2Upgrade.d.mts","default":"./dist/durable/SqlStorageV2Upgrade.mjs"},"./sql-subscription-store":{"types":"./dist/durable/SqlSubscriptionStore.d.mts","default":"./dist/durable/SqlSubscriptionStore.mjs"},"./subagent":{"types":"./dist/capabilities/Subagent.d.mts","default":"./dist/capabilities/Subagent.mjs"},"./subagent-contract":{"types":"./dist/core/SubagentContract.d.mts","default":"./dist/core/SubagentContract.mjs"},"./subagent-host":{"types":"./dist/engine/SubagentHost.d.mts","default":"./dist/engine/SubagentHost.mjs"},"./subagent-reservations":{"types":"./dist/capabilities/SubagentReservations.d.mts","default":"./dist/capabilities/SubagentReservations.mjs"},"./submission-ledger":{"types":"./dist/durable/SubmissionLedger.d.mts","default":"./dist/durable/SubmissionLedger.mjs"},"./submission-status":{"types":"./dist/durable/SubmissionStatus.d.mts","default":"./dist/durable/SubmissionStatus.mjs"},"./subscription":{"types":"./dist/durable/Subscription.d.mts","default":"./dist/durable/Subscription.mjs"},"./subscription-input":{"types":"./dist/durable/SubscriptionInput.d.mts","default":"./dist/durable/SubscriptionInput.mjs"},"./subscription-tools":{"types":"./dist/durable/SubscriptionTools.d.mts","default":"./dist/durable/SubscriptionTools.mjs"},"./subscription-transition":{"types":"./dist/durable/SubscriptionTransition.d.mts","default":"./dist/durable/SubscriptionTransition.mjs"},"./subscriptions":{"types":"./dist/durable/Subscriptions.d.mts","default":"./dist/durable/Subscriptions.mjs"},"./testing/certification":{"types":"./dist/durable/Certification.d.mts","default":"./dist/durable/Certification.mjs"},"./testing/durable-failpoint-test-control":{"types":"./dist/durable/DurableFailpointTestControl.d.mts","default":"./dist/durable/DurableFailpointTestControl.mjs"},"./testing/message-delivery-store-conformance":{"types":"./dist/durable/MessageDeliveryStoreConformance.d.mts","default":"./dist/durable/MessageDeliveryStoreConformance.mjs"},"./testing/schedule-store-conformance":{"types":"./dist/durable/ScheduleStoreConformance.d.mts","default":"./dist/durable/ScheduleStoreConformance.mjs"},"./testing/submission-ledger-conformance":{"types":"./dist/durable/SubmissionLedgerConformance.d.mts","default":"./dist/durable/SubmissionLedgerConformance.mjs"},"./testing/subscription-store-conformance":{"types":"./dist/durable/SubscriptionStoreConformance.d.mts","default":"./dist/durable/SubscriptionStoreConformance.mjs"},"./testing/thread-store-conformance":{"types":"./dist/durable/ThreadStoreConformance.d.mts","default":"./dist/durable/ThreadStoreConformance.mjs"},"./thread":{"types":"./dist/core/Thread.d.mts","default":"./dist/core/Thread.mjs"},"./thread-context-history":{"types":"./dist/durable/ThreadContextHistory.d.mts","default":"./dist/durable/ThreadContextHistory.mjs"},"./thread-context-history-projection":{"types":"./dist/durable/ThreadContextHistoryProjection.d.mts","default":"./dist/durable/ThreadContextHistoryProjection.mjs"},"./thread-history":{"types":"./dist/engine/ThreadHistory.d.mts","default":"./dist/engine/ThreadHistory.mjs"},"./thread-invariants":{"types":"./dist/durable/ThreadInvariants.d.mts","default":"./dist/durable/ThreadInvariants.mjs"},"./thread-projection":{"types":"./dist/durable/ThreadProjection.d.mts","default":"./dist/durable/ThreadProjection.mjs"},"./thread-projection-maintenance":{"types":"./dist/durable/ThreadProjectionMaintenance.d.mts","default":"./dist/durable/ThreadProjectionMaintenance.mjs"},"./thread-store":{"types":"./dist/durable/ThreadStore.d.mts","default":"./dist/durable/ThreadStore.mjs"},"./tool-broker":{"types":"./dist/engine/ToolBroker.d.mts","default":"./dist/engine/ToolBroker.mjs"},"./tool-discovery":{"types":"./dist/capabilities/ToolDiscovery.d.mts","default":"./dist/capabilities/ToolDiscovery.mjs"},"./tool-exposure":{"types":"./dist/ToolExposure.d.mts","default":"./dist/ToolExposure.mjs"},"./tool-reconciler":{"types":"./dist/durable/ToolReconciler.d.mts","default":"./dist/durable/ToolReconciler.mjs"},"./tool-result":{"types":"./dist/core/ToolResult.d.mts","default":"./dist/core/ToolResult.mjs"},"./usage":{"types":"./dist/core/Usage.d.mts","default":"./dist/core/Usage.mjs"},"./wake-scheduler":{"types":"./dist/durable/WakeScheduler.d.mts","default":"./dist/durable/WakeScheduler.mjs"},"./web-capture":{"types":"./dist/capabilities/WebCapture.d.mts","default":"./dist/capabilities/WebCapture.mjs"},"./web-search":{"types":"./dist/capabilities/WebSearch.d.mts","default":"./dist/capabilities/WebSearch.mjs"},"./worker":{"types":"./dist/core/Worker.d.mts","default":"./dist/core/Worker.mjs"},"./worker-host":{"types":"./dist/durable/WorkerHost.d.mts","default":"./dist/durable/WorkerHost.mjs"}},"description":"Effect-native agents, execution, subagents, and sandbox contracts in one tree-shakeable package.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/danieljvdm/effect-agent.git","directory":"packages/effect-agent"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json","test":"vp test --passWithNoTests"}}
|
|
@@ -159,6 +159,21 @@ const isServerRequest = Schema.is(ServerRequest);
|
|
|
159
159
|
const isJsonRpcRequest = (message: unknown): message is RpcMessage.RequestEncoded =>
|
|
160
160
|
isServerRequest(message);
|
|
161
161
|
|
|
162
|
+
/** Effect RPC's tracing extensions are not part of MCP's strict JSON-RPC request shape. */
|
|
163
|
+
const mcpWireMessage = (message: unknown): unknown => {
|
|
164
|
+
if (!Predicate.hasProperty(message, "_tag") || message._tag !== "Request") return message;
|
|
165
|
+
const payload = Predicate.hasProperty(message, "payload") ? message.payload : undefined;
|
|
166
|
+
|
|
167
|
+
return {
|
|
168
|
+
...message,
|
|
169
|
+
payload: payload === null ? undefined : payload,
|
|
170
|
+
traceId: undefined,
|
|
171
|
+
spanId: undefined,
|
|
172
|
+
sampled: undefined,
|
|
173
|
+
headers: [],
|
|
174
|
+
};
|
|
175
|
+
};
|
|
176
|
+
|
|
162
177
|
/** JSON-RPC error a client returns for a server-initiated request it does not serve. */
|
|
163
178
|
const declineServerRequest = (
|
|
164
179
|
request: RpcMessage.RequestEncoded,
|
|
@@ -371,7 +386,7 @@ const makeHttpProtocol = Effect.fn("McpHttpTransport.protocol")(function* (
|
|
|
371
386
|
Effect.sync(() => {
|
|
372
387
|
const encode = (message: unknown): Effect.Effect<string, RpcClientError.RpcClientError> =>
|
|
373
388
|
Effect.suspend(() => {
|
|
374
|
-
const encoded = parser.encode(message);
|
|
389
|
+
const encoded = parser.encode(mcpWireMessage(message));
|
|
375
390
|
|
|
376
391
|
return typeof encoded === "string"
|
|
377
392
|
? Effect.succeed(encoded)
|
|
@@ -599,7 +614,7 @@ const makeStdioProtocol = Effect.fn("McpStdioTransport.protocol")(function* (
|
|
|
599
614
|
const enqueue = (message: unknown): Effect.Effect<void, RpcClientError.RpcClientError> =>
|
|
600
615
|
Effect.suspend(() => {
|
|
601
616
|
if (closed !== undefined) return Effect.fail(closed);
|
|
602
|
-
const encoded = parser.encode(message);
|
|
617
|
+
const encoded = parser.encode(mcpWireMessage(message));
|
|
603
618
|
|
|
604
619
|
if (typeof encoded !== "string") {
|
|
605
620
|
return Effect.fail(protocolDefect("Could not encode an MCP JSON-RPC message"));
|
|
@@ -711,6 +726,7 @@ const executionClassFor = (
|
|
|
711
726
|
};
|
|
712
727
|
|
|
713
728
|
const makeMcpTool = (tool: McpSchema.Tool, trustToolAnnotations: boolean): McpTool => {
|
|
729
|
+
// MCP servers may advertise valid JSON Schemas outside a model provider's strict subset.
|
|
714
730
|
let dynamic: McpTool = Tool.dynamic(tool.name, {
|
|
715
731
|
...(tool.description === undefined ? {} : { description: tool.description }),
|
|
716
732
|
parameters: tool.inputSchema,
|
|
@@ -719,7 +735,7 @@ const makeMcpTool = (tool: McpSchema.Tool, trustToolAnnotations: boolean): McpTo
|
|
|
719
735
|
// MCP reports tool errors inside results so the model can self-correct;
|
|
720
736
|
// `return` hands the typed failure to the model the same way.
|
|
721
737
|
failureMode: "return",
|
|
722
|
-
});
|
|
738
|
+
}).annotate(Tool.Strict, false);
|
|
723
739
|
|
|
724
740
|
const title = tool.title ?? tool.annotations?.title;
|
|
725
741
|
|