@dxos/mcp-client 0.8.4-main.6fa680abb7 → 0.8.4-main.765dc60934

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.
package/LICENSE CHANGED
@@ -1,8 +1,105 @@
1
- MIT License
2
- Copyright (c) 2022 DXOS
1
+ # Functional Source License, Version 1.1, ALv2 Future License
3
2
 
4
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
3
+ ## Abbreviation
5
4
 
6
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
5
+ FSL-1.1-Apache-2.0
7
6
 
8
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
7
+ ## Notice
8
+
9
+ Copyright 2026 DXOS
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the Apache License, Version 2.0 that is effective on the second anniversary of
91
+ the date we make the Software available. On or after that date, you may use the
92
+ Software under the Apache License, Version 2.0, in which case the following
93
+ will apply:
94
+
95
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
+ this file except in compliance with the License.
97
+
98
+ You may obtain a copy of the License at
99
+
100
+ http://www.apache.org/licenses/LICENSE-2.0
101
+
102
+ Unless required by applicable law or agreed to in writing, software distributed
103
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
+ specific language governing permissions and limitations under the License.
package/README.md CHANGED
@@ -18,4 +18,4 @@ pnpm i @dxos/mcp-client
18
18
 
19
19
  Your ideas, issues, and code are most welcome. Please take a look at our [community code of conduct](https://github.com/dxos/dxos/blob/main/CODE_OF_CONDUCT.md), the [issue guide](https://github.com/dxos/dxos/blob/main/CONTRIBUTING.md#submitting-issues), and the [PR contribution guide](https://github.com/dxos/dxos/blob/main/CONTRIBUTING.md#submitting-prs).
20
20
 
21
- License: [MIT](./LICENSE) Copyright 2022 © DXOS
21
+ License: [FSL-1.1-Apache-2.0](./LICENSE) Copyright 2022 © DXOS
@@ -7,6 +7,8 @@ var __export = (target, all) => {
7
7
  // src/McpToolkit.ts
8
8
  var McpToolkit_exports = {};
9
9
  __export(McpToolkit_exports, {
10
+ McpConnectionError: () => McpConnectionError,
11
+ is405: () => is405,
10
12
  make: () => make3
11
13
  });
12
14
  import * as Tool from "@effect/ai/Tool";
@@ -14,21 +16,34 @@ import * as Toolkit from "@effect/ai/Toolkit";
14
16
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
15
17
  import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
16
18
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
19
+ import * as Cause from "effect/Cause";
17
20
  import * as Effect from "effect/Effect";
18
21
  import * as Schema from "effect/Schema";
19
- import { GenericToolkit } from "@dxos/ai";
22
+ import { OpaqueToolkit } from "@dxos/ai";
20
23
  import { invariant } from "@dxos/invariant";
21
- var __dxlog_file = "/__w/dxos/dxos/packages/core/mcp-client/src/McpToolkit.ts";
24
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/compute/mcp-client/src/McpToolkit.ts";
25
+ var McpConnectionError = class extends Schema.TaggedError("McpConnectionError")("McpConnectionError", {
26
+ url: Schema.String,
27
+ protocol: Schema.Literal("sse", "http"),
28
+ message: Schema.String
29
+ }) {
30
+ };
31
+ var CLIENT_INFO = {
32
+ name: "@dxos/mcp-client",
33
+ version: "0.8.3"
34
+ };
22
35
  var make3 = (options) => Effect.gen(function* () {
23
- const transport = createTransport(options.url, options.kind);
24
- const client = new Client({
25
- name: "@dxos/mcp-client",
26
- version: "0.8.3"
36
+ const { client, protocol } = yield* connectWithFallback(options);
37
+ const { tools } = yield* Effect.tryPromise({
38
+ try: () => client.listTools(),
39
+ catch: (cause) => new McpConnectionError({
40
+ url: options.url,
41
+ protocol,
42
+ message: `Failed to list MCP tools: ${formatCause(cause)}`
43
+ })
27
44
  });
28
- yield* Effect.promise(() => client.connect(transport));
29
- const { tools } = yield* Effect.promise(() => client.listTools());
30
45
  if (tools.length === 0) {
31
- return GenericToolkit.empty;
46
+ return OpaqueToolkit.empty;
32
47
  }
33
48
  const effectTools = tools.map((mcpTool) => {
34
49
  const parameters = {};
@@ -65,26 +80,75 @@ var make3 = (options) => Effect.gen(function* () {
65
80
  ];
66
81
  }));
67
82
  const layer = toolkit.toLayer(handlers);
68
- return GenericToolkit.make(toolkit, layer);
83
+ return OpaqueToolkit.make(toolkit, layer);
69
84
  }).pipe(Effect.withSpan("McpToolkit.make"));
70
- var createTransport = (url, kind) => {
85
+ var is405 = (error) => {
86
+ const cause = error != null && typeof error === "object" && "error" in error ? error.error : error;
87
+ return cause instanceof Error && cause.message.includes("405");
88
+ };
89
+ var connectWithFallback = (options) => Effect.gen(function* () {
90
+ const fallbackProtocol = options.protocol === "sse" ? "http" : "sse";
91
+ const primary = yield* connectClient(options.url, options.protocol, options.apiKey).pipe(Effect.either);
92
+ if (primary._tag === "Right") {
93
+ return {
94
+ client: primary.right,
95
+ protocol: options.protocol
96
+ };
97
+ }
98
+ if (is405(primary.left)) {
99
+ const fallback = yield* connectClient(options.url, fallbackProtocol, options.apiKey).pipe(Effect.either);
100
+ if (fallback._tag === "Right") {
101
+ return {
102
+ client: fallback.right,
103
+ protocol: fallbackProtocol
104
+ };
105
+ }
106
+ return yield* Effect.fail(new McpConnectionError({
107
+ url: options.url,
108
+ protocol: fallbackProtocol,
109
+ message: `Failed to connect via ${fallbackProtocol} after 405 fallback: ${formatCause(fallback.left)}`
110
+ }));
111
+ }
112
+ return yield* Effect.fail(new McpConnectionError({
113
+ url: options.url,
114
+ protocol: options.protocol,
115
+ message: `Failed to connect via ${options.protocol}: ${formatCause(primary.left)}`
116
+ }));
117
+ });
118
+ var connectClient = (url, protocol, apiKey) => Effect.tryPromise(() => {
119
+ const client = new Client(CLIENT_INFO);
120
+ const transport = createTransport(url, protocol, apiKey);
121
+ return client.connect(transport).then(() => client);
122
+ });
123
+ var formatCause = (error) => {
124
+ const inner = error != null && typeof error === "object" && "error" in error ? error.error : error;
125
+ if (inner instanceof Error) {
126
+ return inner.message;
127
+ }
128
+ if (Cause.isCause(error)) {
129
+ return Cause.pretty(error);
130
+ }
131
+ return String(inner);
132
+ };
133
+ var createTransport = (url, protocol, apiKey) => {
71
134
  const urlObj = new URL(url);
72
- switch (kind) {
135
+ const requestInit = apiKey ? {
136
+ headers: {
137
+ Authorization: `Bearer ${apiKey}`
138
+ }
139
+ } : void 0;
140
+ switch (protocol) {
73
141
  case "sse":
74
- return new SSEClientTransport(urlObj);
142
+ return new SSEClientTransport(urlObj, {
143
+ requestInit
144
+ });
75
145
  case "http":
76
- return new StreamableHTTPClientTransport(urlObj);
77
- default: {
78
- const _exhaustive = kind;
79
- return invariant(false, `Unsupported MCP transport kind: ${_exhaustive}`, {
80
- F: __dxlog_file,
81
- L: 107,
82
- S: void 0,
83
- A: [
84
- "false",
85
- "`Unsupported MCP transport kind: ${_exhaustive}`"
86
- ]
146
+ return new StreamableHTTPClientTransport(urlObj, {
147
+ requestInit
87
148
  });
149
+ default: {
150
+ const _exhaustive = protocol;
151
+ return invariant(false, `Unsupported MCP transport protocol: ${_exhaustive}`, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 169, S: void 0, A: ["false", "`Unsupported MCP transport protocol: ${_exhaustive}`"] });
88
152
  }
89
153
  }
90
154
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/McpToolkit.ts"],
4
- "sourcesContent": ["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Tool from '@effect/ai/Tool';\nimport * as Toolkit from '@effect/ai/Toolkit';\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { GenericToolkit } from '@dxos/ai';\nimport { invariant } from '@dxos/invariant';\n\nexport interface McpToolkitOptions {\n url: string;\n kind: 'sse' | 'http';\n}\n\n/**\n * Creates a GenericToolkit that connects to an MCP server and exposes its tools to the assistant.\n *\n * @param options MCP server URL and transport kind ('sse' for SSE, 'http' for Streamable HTTP).\n * @returns A GenericToolkit containing all tools from the MCP server.\n */\nexport const make = (options: McpToolkitOptions): Effect.Effect<GenericToolkit.GenericToolkit> =>\n Effect.gen(function* () {\n const transport = createTransport(options.url, options.kind);\n const client = new Client({ name: '@dxos/mcp-client', version: '0.8.3' });\n yield* Effect.promise(() => client.connect(transport));\n\n const { tools } = yield* Effect.promise(() => client.listTools());\n\n if (tools.length === 0) {\n return GenericToolkit.empty;\n }\n\n const effectTools = tools.map((mcpTool) => {\n const parameters: any = {};\n for (const [key, value] of Object.entries(mcpTool.inputSchema.properties ?? {})) {\n if (mcpTool.inputSchema.required?.includes(key)) {\n parameters[key] = Schema.Unknown.pipe(\n Schema.annotations({\n jsonSchema: value,\n }),\n );\n } else {\n parameters[key] = Schema.Unknown.pipe(\n Schema.annotations({\n jsonSchema: value,\n }),\n ).pipe(Schema.optional);\n }\n }\n\n return Tool.make(sanitizeToolName(mcpTool.name), {\n description: mcpTool.description ?? `MCP tool: ${mcpTool.name}`,\n parameters,\n success: Schema.String,\n failure: Schema.Never,\n });\n });\n\n const toolkit = Toolkit.make(...effectTools);\n\n const handlers = Object.fromEntries(\n tools.map((mcpTool) => {\n const toolName = sanitizeToolName(mcpTool.name);\n return [\n toolName,\n Effect.fn(function* (args: unknown) {\n const result = yield* Effect.promise(() =>\n client.callTool({\n name: mcpTool.name,\n arguments: args as any,\n }),\n );\n return formatToolResult(result);\n }),\n ];\n }),\n ) as any;\n\n const layer = toolkit.toLayer(handlers);\n\n return GenericToolkit.make(toolkit, layer);\n }).pipe(Effect.withSpan('McpToolkit.make'));\n\n/**\n * Creates a transport for the given MCP server URL and kind.\n */\nconst createTransport = (\n url: string,\n kind: McpToolkitOptions['kind'],\n): SSEClientTransport | StreamableHTTPClientTransport => {\n const urlObj = new URL(url);\n switch (kind) {\n case 'sse':\n return new SSEClientTransport(urlObj);\n case 'http':\n return new StreamableHTTPClientTransport(urlObj);\n default: {\n const _exhaustive: never = kind;\n return invariant(false, `Unsupported MCP transport kind: ${_exhaustive}`) as never;\n }\n }\n};\n\n/**\n * Sanitizes MCP tool names for use as Effect tool names (replaces / with _).\n */\nconst sanitizeToolName = (name: string): string => name.replace(/\\//g, '_');\n\n/**\n * Formats MCP callTool result content for the assistant.\n */\nconst formatToolResult = (result: Awaited<ReturnType<Client['callTool']>>): string => {\n if ('toolResult' in result && result.toolResult !== undefined) {\n return JSON.stringify(result.toolResult);\n }\n if ('content' in result && Array.isArray(result.content)) {\n return result.content\n .filter((part): part is { type: 'text'; text: string } => part.type === 'text')\n .map((part) => part.text)\n .join('\\n');\n }\n return String(result);\n};\n"],
5
- "mappings": ";;;;;;;AAAA;;cAAAA;;AAMA,YAAYC,UAAU;AACtB,YAAYC,aAAa;AACzB,SAASC,cAAc;AACvB,SAASC,0BAA0B;AACnC,SAASC,qCAAqC;AAC9C,YAAYC,YAAY;AACxB,YAAYC,YAAY;AAExB,SAASC,sBAAsB;AAC/B,SAASC,iBAAiB;;AAanB,IAAMT,QAAO,CAACU,YACZC,WAAI,aAAA;AACT,QAAMC,YAAYC,gBAAgBH,QAAQI,KAAKJ,QAAQK,IAAI;AAC3D,QAAMC,SAAS,IAAIb,OAAO;IAAEc,MAAM;IAAoBC,SAAS;EAAQ,CAAA;AACvE,SAAcC,eAAQ,MAAMH,OAAOI,QAAQR,SAAAA,CAAAA;AAE3C,QAAM,EAAES,MAAK,IAAK,OAAcF,eAAQ,MAAMH,OAAOM,UAAS,CAAA;AAE9D,MAAID,MAAME,WAAW,GAAG;AACtB,WAAOf,eAAegB;EACxB;AAEA,QAAMC,cAAcJ,MAAMK,IAAI,CAACC,YAAAA;AAC7B,UAAMC,aAAkB,CAAC;AACzB,eAAW,CAACC,KAAKC,KAAAA,KAAUC,OAAOC,QAAQL,QAAQM,YAAYC,cAAc,CAAC,CAAA,GAAI;AAC/E,UAAIP,QAAQM,YAAYE,UAAUC,SAASP,GAAAA,GAAM;AAC/CD,mBAAWC,GAAAA,IAAcQ,eAAQC,KACxBC,mBAAY;UACjBC,YAAYV;QACd,CAAA,CAAA;MAEJ,OAAO;AACLF,mBAAWC,GAAAA,IAAcQ,eAAQC,KACxBC,mBAAY;UACjBC,YAAYV;QACd,CAAA,CAAA,EACAQ,KAAYG,eAAQ;MACxB;IACF;AAEA,WAAYzC,UAAK0C,iBAAiBf,QAAQV,IAAI,GAAG;MAC/C0B,aAAahB,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AKC,SAAS,MAAA,EACvEhD,IAAI,CAAC+C,SAASA,KAAKE,IAAI,EACvBC,KAAK,IAAA;EACV;AACA,SAAO/B,OAAOS,MAAAA;AAChB;",
6
- "names": ["make", "Tool", "Toolkit", "Client", "SSEClientTransport", "StreamableHTTPClientTransport", "Effect", "Schema", "GenericToolkit", "invariant", "options", "gen", "transport", "createTransport", "url", "kind", "client", "name", "version", "promise", "connect", "tools", "listTools", "length", "empty", "effectTools", "map", "mcpTool", "parameters", "key", "value", "Object", "entries", "inputSchema", "properties", "required", "includes", "Unknown", "pipe", "annotations", "jsonSchema", "optional", "sanitizeToolName", "description", "success", "String", "failure", "Never", "toolkit", "handlers", "fromEntries", "toolName", "fn", "args", "result", "callTool", "arguments", "formatToolResult", "layer", "toLayer", "withSpan", "urlObj", "URL", "_exhaustive", "replace", "toolResult", "undefined", "JSON", "stringify", "Array", "isArray", "content", "filter", "part", "type", "text", "join"]
4
+ "sourcesContent": ["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Tool from '@effect/ai/Tool';\nimport * as Toolkit from '@effect/ai/Toolkit';\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js';\n// SSEClientTransport is marked @deprecated in the SDK in favor of StreamableHTTP, but the\n// SDK itself notes that clients should keep supporting both while servers migrate.\n// `connectWithFallback` below tries the configured protocol first, then the other on 405.\n// eslint-disable-next-line @typescript-eslint/no-deprecated\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport * as Cause from 'effect/Cause';\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { OpaqueToolkit } from '@dxos/ai';\nimport { invariant } from '@dxos/invariant';\n\n/**\n * Typed failure raised when the MCP client cannot connect or list tools.\n * Carries the underlying cause and the server URL for diagnostics.\n */\nexport class McpConnectionError extends Schema.TaggedError<McpConnectionError>('McpConnectionError')(\n 'McpConnectionError',\n {\n url: Schema.String,\n protocol: Schema.Literal('sse', 'http'),\n message: Schema.String,\n },\n) {}\n\n/**\n * Creates an OpaqueToolkit that connects to an MCP server and exposes its tools to the assistant.\n *\n * @param options MCP server URL and transport protocol ('http' for Streamable HTTP, 'sse' for SSE).\n * @returns An OpaqueToolkit containing all tools from the MCP server.\n */\nconst CLIENT_INFO = { name: '@dxos/mcp-client', version: '0.8.3' };\n\nexport interface McpToolkitOptions {\n url: string;\n protocol: 'sse' | 'http';\n apiKey?: string;\n}\n\nexport const make = (options: McpToolkitOptions): Effect.Effect<OpaqueToolkit.OpaqueToolkit, McpConnectionError> =>\n Effect.gen(function* () {\n const { client, protocol } = yield* connectWithFallback(options);\n\n const { tools } = yield* Effect.tryPromise({\n try: () => client.listTools(),\n catch: (cause) =>\n new McpConnectionError({\n url: options.url,\n protocol,\n message: `Failed to list MCP tools: ${formatCause(cause)}`,\n }),\n });\n if (tools.length === 0) {\n return OpaqueToolkit.empty;\n }\n\n const effectTools = tools.map((mcpTool) => {\n const parameters: any = {};\n for (const [key, value] of Object.entries(mcpTool.inputSchema.properties ?? {})) {\n if (mcpTool.inputSchema.required?.includes(key)) {\n parameters[key] = Schema.Unknown.pipe(Schema.annotations({ jsonSchema: value }));\n } else {\n parameters[key] = Schema.Unknown.pipe(Schema.annotations({ jsonSchema: value })).pipe(Schema.optional);\n }\n }\n\n return Tool.make(sanitizeToolName(mcpTool.name), {\n description: mcpTool.description ?? `MCP tool: ${mcpTool.name}`,\n parameters,\n success: Schema.String,\n failure: Schema.Never,\n });\n });\n\n const toolkit = Toolkit.make(...effectTools);\n\n const handlers = Object.fromEntries(\n tools.map((mcpTool) => {\n const toolName = sanitizeToolName(mcpTool.name);\n return [\n toolName,\n Effect.fn(function* (args: unknown) {\n const result = yield* Effect.promise(() =>\n client.callTool({\n name: mcpTool.name,\n arguments: args as any,\n }),\n );\n return formatToolResult(result);\n }),\n ];\n }),\n ) as any;\n\n const layer = toolkit.toLayer(handlers);\n\n return OpaqueToolkit.make(toolkit, layer);\n }).pipe(Effect.withSpan('McpToolkit.make'));\n\n/**\n * Returns true when the error (or its wrapped cause) contains a 405 status code.\n * `Effect.tryPromise` wraps thrown errors in `UnknownException`, so we unwrap first.\n */\nexport const is405 = (error: unknown): boolean => {\n const cause = error != null && typeof error === 'object' && 'error' in error ? (error as any).error : error;\n return cause instanceof Error && cause.message.includes('405');\n};\n\n/**\n * Connects to an MCP server, falling back to the alternate transport on 405 errors.\n * Per the MCP spec, a 405 indicates the server uses the other transport protocol.\n * Returns the connected Client (a fresh instance is created for the fallback attempt).\n *\n * Failures are surfaced as typed `McpConnectionError` so callers can recover (e.g. drop\n * the misconfigured server) without breaking the surrounding effect.\n */\nconst connectWithFallback = (\n options: McpToolkitOptions,\n): Effect.Effect<{ client: Client; protocol: McpToolkitOptions['protocol'] }, McpConnectionError> =>\n Effect.gen(function* () {\n const fallbackProtocol = options.protocol === 'sse' ? 'http' : 'sse';\n const primary = yield* connectClient(options.url, options.protocol, options.apiKey).pipe(Effect.either);\n if (primary._tag === 'Right') {\n return { client: primary.right, protocol: options.protocol };\n }\n if (is405(primary.left)) {\n const fallback = yield* connectClient(options.url, fallbackProtocol, options.apiKey).pipe(Effect.either);\n if (fallback._tag === 'Right') {\n return { client: fallback.right, protocol: fallbackProtocol };\n }\n return yield* Effect.fail(\n new McpConnectionError({\n url: options.url,\n protocol: fallbackProtocol,\n message: `Failed to connect via ${fallbackProtocol} after 405 fallback: ${formatCause(fallback.left)}`,\n }),\n );\n }\n return yield* Effect.fail(\n new McpConnectionError({\n url: options.url,\n protocol: options.protocol,\n message: `Failed to connect via ${options.protocol}: ${formatCause(primary.left)}`,\n }),\n );\n });\n\nconst connectClient = (url: string, protocol: McpToolkitOptions['protocol'], apiKey?: string) =>\n Effect.tryPromise(() => {\n const client = new Client(CLIENT_INFO);\n const transport = createTransport(url, protocol, apiKey);\n return client.connect(transport).then(() => client);\n });\n\n/**\n * Renders a thrown value to a short string for inclusion in error messages.\n * `Effect.tryPromise` wraps thrown errors in `UnknownException`; unwrap when present.\n */\nconst formatCause = (error: unknown): string => {\n const inner = error != null && typeof error === 'object' && 'error' in error ? (error as any).error : error;\n if (inner instanceof Error) {\n return inner.message;\n }\n if (Cause.isCause(error)) {\n return Cause.pretty(error);\n }\n\n return String(inner);\n};\n\n/**\n * Creates a transport for the given MCP server URL and protocol.\n */\nconst createTransport = (\n url: string,\n protocol: McpToolkitOptions['protocol'],\n apiKey?: string,\n): SSEClientTransport | StreamableHTTPClientTransport => {\n const urlObj = new URL(url);\n const requestInit: RequestInit | undefined = apiKey ? { headers: { Authorization: `Bearer ${apiKey}` } } : undefined;\n switch (protocol) {\n case 'sse':\n return new SSEClientTransport(urlObj, { requestInit });\n case 'http':\n return new StreamableHTTPClientTransport(urlObj, { requestInit });\n default: {\n const _exhaustive: never = protocol;\n return invariant(false, `Unsupported MCP transport protocol: ${_exhaustive}`) as never;\n }\n }\n};\n\n/**\n * Sanitizes MCP tool names for use as Effect tool names (replaces / with _).\n */\nconst sanitizeToolName = (name: string): string => name.replace(/\\//g, '_');\n\n/**\n * Formats MCP callTool result content for the assistant.\n */\nconst formatToolResult = (result: Awaited<ReturnType<Client['callTool']>>): string => {\n if ('toolResult' in result && result.toolResult !== undefined) {\n return JSON.stringify(result.toolResult);\n }\n if ('content' in result && Array.isArray(result.content)) {\n return result.content\n .filter((part): part is { type: 'text'; text: string } => part.type === 'text')\n .map((part) => part.text)\n .join('\\n');\n }\n\n return String(result);\n};\n"],
5
+ "mappings": ";;;;;;;AAAA;;;;cAAAA;;AAMA,YAAYC,UAAU;AACtB,YAAYC,aAAa;AACzB,SAASC,cAAc;AAKvB,SAASC,0BAA0B;AACnC,SAASC,qCAAqC;AAC9C,YAAYC,WAAW;AACvB,YAAYC,YAAY;AACxB,YAAYC,YAAY;AAExB,SAASC,qBAAqB;AAC9B,SAASC,iBAAiB;AAE1B,IAAA,eAAA;AAQIC,IAAUH,qBAAVG,cAAgC,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;AAME,IAAII,cAAAA,CAAiBX,UAAO;QAC1B,QAAOW,SAAM7C,QAAO,OAAA,UAAA,YAAA,WAAA,QAAA,MAAA,QAAA;AACtB,MAAA,iBAAA,OAAA;AACIN,WAAMoD,MAAO;;AAEjB,MAAA,cAAA,KAAA,GAAA;AAEA,WAAcD,aAAAA,KAAAA;EAChB;AAEA,SAAA,OAAA,KAAA;;AASE,IAAME,kBAAuCJ,CAAAA,KAAS,UAAA,WAAA;QAAEK,SAAS,IAAA,IAAA,GAAA;sBAAEC,SAAgB;IAAkB,SAAA;MAAMC,eAAAA,UAAAA,MAAAA;IAC3G;MACE;oBACS;;AAA6C,aAAA,IAAA,mBAAA,QAAA;QACjD;MACH,CAAA;;AAA+D,aAAA,IAAA,8BAAA,QAAA;QACjE;MAAS,CAAA;;AAGT,YAAA,cAAA;AACF,aAAA,UAAA,OAAA,uCAAA,WAAA,IAAA,EAAA,YAAA,YAAA,GAAA,cAAA,GAAA,KAAA,GAAA,QAAA,GAAA,CAAA,SAAA,sDAAA,EAAA,CAAA;IACF;EAEA;;;IAUI,mBAAqB,CAACC,WAAOC;AAC/B,MAAA,gBAAA,UAAA,OAAA,eAAA,QAAA;AACI,WAAA,KAAA,UAAaD,OAAgBE,UAAQF;;AAKzC,MAAA,aAAA,UAAA,MAAA,QAAA,OAAA,OAAA,GAAA;AAEA,WAAO3B,OAAO2B,QAAAA,OAAAA,CAAAA,SAAAA,KAAAA,SAAAA,MAAAA,EAAAA,IAAAA,CAAAA,SAAAA,KAAAA,IAAAA,EAAAA,KAAAA,IAAAA;EAChB;;;",
6
+ "names": ["make", "Tool", "Toolkit", "Client", "SSEClientTransport", "StreamableHTTPClientTransport", "Cause", "Effect", "Schema", "OpaqueToolkit", "invariant", "protocol", "message", "version", "tools", "tryPromise", "try", "client", "listTools", "catch", "cause", "McpConnectionError", "url", "options", "effectTools", "key", "value", "Object", "entries", "inputSchema", "parameters", "Unknown", "pipe", "annotations", "jsonSchema", "success", "String", "failure", "sanitizeToolName", "mcpTool", "toolName", "name", "arguments", "args", "formatToolResult", "withSpan", "Error", "connectClient", "primary", "is405", "fallback", "_tag", "fallbackProtocol", "transport", "createTransport", "apiKey", "connect", "inner", "isCause", "requestInit", "headers", "Authorization", "undefined", "result", "toolResult", "isArray"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"src/McpToolkit.ts":{"bytes":14532,"imports":[{"path":"@effect/ai/Tool","kind":"import-statement","external":true},{"path":"@effect/ai/Toolkit","kind":"import-statement","external":true},{"path":"@modelcontextprotocol/sdk/client/index.js","kind":"import-statement","external":true},{"path":"@modelcontextprotocol/sdk/client/sse.js","kind":"import-statement","external":true},{"path":"@modelcontextprotocol/sdk/client/streamableHttp.js","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Schema","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"format":"esm"},"src/index.ts":{"bytes":527,"imports":[{"path":"src/McpToolkit.ts","kind":"import-statement","original":"./McpToolkit"}],"format":"esm"}},"outputs":{"dist/lib/neutral/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":7367},"dist/lib/neutral/index.mjs":{"imports":[{"path":"@effect/ai/Tool","kind":"import-statement","external":true},{"path":"@effect/ai/Toolkit","kind":"import-statement","external":true},{"path":"@modelcontextprotocol/sdk/client/index.js","kind":"import-statement","external":true},{"path":"@modelcontextprotocol/sdk/client/sse.js","kind":"import-statement","external":true},{"path":"@modelcontextprotocol/sdk/client/streamableHttp.js","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Schema","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"exports":["McpToolkit"],"entryPoint":"src/index.ts","inputs":{"src/McpToolkit.ts":{"bytesInOutput":3270},"src/index.ts":{"bytesInOutput":0}},"bytes":3541}}}
1
+ {"inputs":{"src/McpToolkit.ts":{"bytes":26854,"imports":[{"path":"@effect/ai/Tool","kind":"import-statement","external":true},{"path":"@effect/ai/Toolkit","kind":"import-statement","external":true},{"path":"@modelcontextprotocol/sdk/client/index.js","kind":"import-statement","external":true},{"path":"@modelcontextprotocol/sdk/client/sse.js","kind":"import-statement","external":true},{"path":"@modelcontextprotocol/sdk/client/streamableHttp.js","kind":"import-statement","external":true},{"path":"effect/Cause","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Schema","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"format":"esm"},"src/index.ts":{"bytes":452,"imports":[{"path":"src/McpToolkit.ts","kind":"import-statement","original":"./McpToolkit"}],"format":"esm"}},"outputs":{"dist/lib/neutral/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":12362},"dist/lib/neutral/index.mjs":{"imports":[{"path":"@effect/ai/Tool","kind":"import-statement","external":true},{"path":"@effect/ai/Toolkit","kind":"import-statement","external":true},{"path":"@modelcontextprotocol/sdk/client/index.js","kind":"import-statement","external":true},{"path":"@modelcontextprotocol/sdk/client/sse.js","kind":"import-statement","external":true},{"path":"@modelcontextprotocol/sdk/client/streamableHttp.js","kind":"import-statement","external":true},{"path":"effect/Cause","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Schema","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"exports":["McpToolkit"],"entryPoint":"src/index.ts","inputs":{"src/McpToolkit.ts":{"bytesInOutput":5642},"src/index.ts":{"bytesInOutput":0}},"bytes":5913}}}
@@ -1,14 +1,29 @@
1
1
  import * as Effect from 'effect/Effect';
2
- import { GenericToolkit } from '@dxos/ai';
2
+ import * as Schema from 'effect/Schema';
3
+ import { OpaqueToolkit } from '@dxos/ai';
4
+ declare const McpConnectionError_base: Schema.TaggedErrorClass<McpConnectionError, "McpConnectionError", {
5
+ readonly _tag: Schema.tag<"McpConnectionError">;
6
+ } & {
7
+ url: typeof Schema.String;
8
+ protocol: Schema.Literal<["sse", "http"]>;
9
+ message: typeof Schema.String;
10
+ }>;
11
+ /**
12
+ * Typed failure raised when the MCP client cannot connect or list tools.
13
+ * Carries the underlying cause and the server URL for diagnostics.
14
+ */
15
+ export declare class McpConnectionError extends McpConnectionError_base {
16
+ }
3
17
  export interface McpToolkitOptions {
4
18
  url: string;
5
- kind: 'sse' | 'http';
19
+ protocol: 'sse' | 'http';
20
+ apiKey?: string;
6
21
  }
22
+ export declare const make: (options: McpToolkitOptions) => Effect.Effect<OpaqueToolkit.OpaqueToolkit, McpConnectionError>;
7
23
  /**
8
- * Creates a GenericToolkit that connects to an MCP server and exposes its tools to the assistant.
9
- *
10
- * @param options MCP server URL and transport kind ('sse' for SSE, 'http' for Streamable HTTP).
11
- * @returns A GenericToolkit containing all tools from the MCP server.
24
+ * Returns true when the error (or its wrapped cause) contains a 405 status code.
25
+ * `Effect.tryPromise` wraps thrown errors in `UnknownException`, so we unwrap first.
12
26
  */
13
- export declare const make: (options: McpToolkitOptions) => Effect.Effect<GenericToolkit.GenericToolkit>;
27
+ export declare const is405: (error: unknown) => boolean;
28
+ export {};
14
29
  //# sourceMappingURL=McpToolkit.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"McpToolkit.d.ts","sourceRoot":"","sources":["../../../src/McpToolkit.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAGxC,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAG1C,MAAM,WAAW,iBAAiB;IAChC,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,KAAK,GAAG,MAAM,CAAC;CACtB;AAED;;;;;GAKG;AACH,eAAO,MAAM,IAAI,GAAI,SAAS,iBAAiB,KAAG,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,cAAc,CA6DhD,CAAC"}
1
+ {"version":3,"file":"McpToolkit.d.ts","sourceRoot":"","sources":["../../../src/McpToolkit.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AACxC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAExC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;;;;;;;;AAGzC;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,uBAOvC;CAAG;AAUJ,MAAM,WAAW,iBAAiB;IAChC,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,KAAK,GAAG,MAAM,CAAC;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,eAAO,MAAM,IAAI,YAAa,iBAAiB,KAAG,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,aAAa,EAAE,kBAAkB,CA0DlE,CAAC;AAE9C;;;GAGG;AACH,eAAO,MAAM,KAAK,UAAW,OAAO,KAAG,OAGtC,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=is405.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"is405.test.d.ts","sourceRoot":"","sources":["../../../src/is405.test.ts"],"names":[],"mappings":""}