@fgv/ts-extras-mcp 5.1.0-34

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.
Files changed (107) hide show
  1. package/.rush/temp/5d207610a84e494acaefe7ed13447cda74ddf7da.tar.log +90 -0
  2. package/.rush/temp/chunked-rush-logs/ts-extras-mcp.build.chunks.jsonl +9 -0
  3. package/.rush/temp/operation/build/all.log +9 -0
  4. package/.rush/temp/operation/build/log-chunks.jsonl +9 -0
  5. package/.rush/temp/operation/build/state.json +3 -0
  6. package/.rush/temp/shrinkwrap-deps.json +734 -0
  7. package/CHANGELOG.json +4 -0
  8. package/README.md +133 -0
  9. package/config/api-extractor.json +38 -0
  10. package/config/jest.config.json +13 -0
  11. package/config/rig.json +6 -0
  12. package/dist/index.js +49 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/packlets/mcp/adapter.js +122 -0
  15. package/dist/packlets/mcp/adapter.js.map +1 -0
  16. package/dist/packlets/mcp/index.js +33 -0
  17. package/dist/packlets/mcp/index.js.map +1 -0
  18. package/dist/packlets/mcp/model.js +23 -0
  19. package/dist/packlets/mcp/model.js.map +1 -0
  20. package/dist/packlets/mcp/operations.js +119 -0
  21. package/dist/packlets/mcp/operations.js.map +1 -0
  22. package/dist/packlets/mcp/sdk.js +67 -0
  23. package/dist/packlets/mcp/sdk.js.map +1 -0
  24. package/dist/packlets/mcp/session.js +109 -0
  25. package/dist/packlets/mcp/session.js.map +1 -0
  26. package/dist/packlets/mcp/transports.js +96 -0
  27. package/dist/packlets/mcp/transports.js.map +1 -0
  28. package/dist/test/unit/endToEnd.test.js +220 -0
  29. package/dist/test/unit/endToEnd.test.js.map +1 -0
  30. package/dist/test/unit/index.test.js +41 -0
  31. package/dist/test/unit/index.test.js.map +1 -0
  32. package/dist/test/unit/mcp.test.js +381 -0
  33. package/dist/test/unit/mcp.test.js.map +1 -0
  34. package/dist/test/unit/sdk.test.js +68 -0
  35. package/dist/test/unit/sdk.test.js.map +1 -0
  36. package/dist/ts-extras-mcp.d.ts +290 -0
  37. package/dist/tsdoc-metadata.json +11 -0
  38. package/eslint.config.js +15 -0
  39. package/etc/ts-extras-mcp.api.md +104 -0
  40. package/lib/index.d.ts +28 -0
  41. package/lib/index.d.ts.map +1 -0
  42. package/lib/index.js +65 -0
  43. package/lib/index.js.map +1 -0
  44. package/lib/packlets/mcp/adapter.d.ts +33 -0
  45. package/lib/packlets/mcp/adapter.d.ts.map +1 -0
  46. package/lib/packlets/mcp/adapter.js +125 -0
  47. package/lib/packlets/mcp/adapter.js.map +1 -0
  48. package/lib/packlets/mcp/index.d.ts +10 -0
  49. package/lib/packlets/mcp/index.d.ts.map +1 -0
  50. package/lib/packlets/mcp/index.js +57 -0
  51. package/lib/packlets/mcp/index.js.map +1 -0
  52. package/lib/packlets/mcp/model.d.ts +155 -0
  53. package/lib/packlets/mcp/model.d.ts.map +1 -0
  54. package/lib/packlets/mcp/model.js +24 -0
  55. package/lib/packlets/mcp/model.js.map +1 -0
  56. package/lib/packlets/mcp/operations.d.ts +36 -0
  57. package/lib/packlets/mcp/operations.d.ts.map +1 -0
  58. package/lib/packlets/mcp/operations.js +123 -0
  59. package/lib/packlets/mcp/operations.js.map +1 -0
  60. package/lib/packlets/mcp/sdk.d.ts +91 -0
  61. package/lib/packlets/mcp/sdk.d.ts.map +1 -0
  62. package/lib/packlets/mcp/sdk.js +72 -0
  63. package/lib/packlets/mcp/sdk.js.map +1 -0
  64. package/lib/packlets/mcp/session.d.ts +43 -0
  65. package/lib/packlets/mcp/session.d.ts.map +1 -0
  66. package/lib/packlets/mcp/session.js +115 -0
  67. package/lib/packlets/mcp/session.js.map +1 -0
  68. package/lib/packlets/mcp/transports.d.ts +49 -0
  69. package/lib/packlets/mcp/transports.d.ts.map +1 -0
  70. package/lib/packlets/mcp/transports.js +102 -0
  71. package/lib/packlets/mcp/transports.js.map +1 -0
  72. package/lib/test/unit/endToEnd.test.d.ts +13 -0
  73. package/lib/test/unit/endToEnd.test.d.ts.map +1 -0
  74. package/lib/test/unit/endToEnd.test.js +222 -0
  75. package/lib/test/unit/endToEnd.test.js.map +1 -0
  76. package/lib/test/unit/index.test.d.ts +2 -0
  77. package/lib/test/unit/index.test.d.ts.map +1 -0
  78. package/lib/test/unit/index.test.js +76 -0
  79. package/lib/test/unit/index.test.js.map +1 -0
  80. package/lib/test/unit/mcp.test.d.ts +2 -0
  81. package/lib/test/unit/mcp.test.d.ts.map +1 -0
  82. package/lib/test/unit/mcp.test.js +416 -0
  83. package/lib/test/unit/mcp.test.js.map +1 -0
  84. package/lib/test/unit/sdk.test.d.ts +2 -0
  85. package/lib/test/unit/sdk.test.d.ts.map +1 -0
  86. package/lib/test/unit/sdk.test.js +70 -0
  87. package/lib/test/unit/sdk.test.js.map +1 -0
  88. package/package.json +86 -0
  89. package/rush-logs/ts-extras-mcp.build.cache.log +3 -0
  90. package/rush-logs/ts-extras-mcp.build.log +9 -0
  91. package/src/index.ts +50 -0
  92. package/src/packlets/mcp/adapter.ts +152 -0
  93. package/src/packlets/mcp/index.ts +34 -0
  94. package/src/packlets/mcp/model.ts +204 -0
  95. package/src/packlets/mcp/operations.ts +138 -0
  96. package/src/packlets/mcp/sdk.ts +148 -0
  97. package/src/packlets/mcp/session.ts +137 -0
  98. package/src/packlets/mcp/transports.ts +111 -0
  99. package/src/test/unit/endToEnd.test.ts +254 -0
  100. package/src/test/unit/index.test.ts +43 -0
  101. package/src/test/unit/mcp.test.ts +473 -0
  102. package/src/test/unit/sdk.test.ts +73 -0
  103. package/temp/build/lint/_eslint-5eVG3S6w.json +54 -0
  104. package/temp/build/typescript/ts_8nwakTlr.json +1 -0
  105. package/temp/ts-extras-mcp.api.json +1662 -0
  106. package/temp/ts-extras-mcp.api.md +104 -0
  107. package/tsconfig.json +12 -0
package/package.json ADDED
@@ -0,0 +1,86 @@
1
+ {
2
+ "name": "@fgv/ts-extras-mcp",
3
+ "version": "5.1.0-34",
4
+ "description": "Result-integration boundary over @modelcontextprotocol/sdk: connect to MCP servers, discover tools, and adapt them into @fgv/ts-extras ai-assist client tools",
5
+ "main": "lib/index.js",
6
+ "types": "dist/ts-extras-mcp.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "node": {
10
+ "import": "./lib/index.js",
11
+ "require": "./lib/index.js"
12
+ },
13
+ "default": {
14
+ "import": "./lib/index.js",
15
+ "require": "./lib/index.js"
16
+ },
17
+ "types": "./dist/ts-extras-mcp.d.ts"
18
+ }
19
+ },
20
+ "scripts": {
21
+ "build": "heft build --clean",
22
+ "clean": "heft clean",
23
+ "test": "heft test --clean",
24
+ "test-handles": "jest --runInBand --detectOpenHandles",
25
+ "clean-jest": "jest --clear-cache",
26
+ "update-snapshot": "jest --updateSnapshot",
27
+ "coverage": "jest --coverage",
28
+ "lint": "eslint src --ext .ts",
29
+ "fixlint": "eslint src --ext .ts --fix"
30
+ },
31
+ "keywords": [
32
+ "typescript",
33
+ "mcp",
34
+ "model-context-protocol",
35
+ "ai-assist",
36
+ "client-tools",
37
+ "result"
38
+ ],
39
+ "author": "Erik Fortune",
40
+ "license": "MIT",
41
+ "bugs": {
42
+ "url": "https://github.com/ErikFortune/fgv/issues"
43
+ },
44
+ "homepage": "https://github.com/ErikFortune/fgv/tree/main/libraries/ts-extras-mcp#readme",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "https://github.com/ErikFortune/fgv.git"
48
+ },
49
+ "sideEffects": false,
50
+ "dependencies": {
51
+ "@modelcontextprotocol/sdk": "^1.29.0"
52
+ },
53
+ "devDependencies": {
54
+ "@fgv/heft-dual-rig": "workspace:*",
55
+ "@fgv/ts-utils": "workspace:*",
56
+ "@fgv/ts-extras": "workspace:*",
57
+ "@fgv/ts-json-base": "workspace:*",
58
+ "@fgv/ts-utils-jest": "workspace:*",
59
+ "@microsoft/api-extractor": "^7.55.2",
60
+ "@rushstack/eslint-config": "4.6.4",
61
+ "@rushstack/heft": "1.2.7",
62
+ "@rushstack/heft-jest-plugin": "1.2.6",
63
+ "@rushstack/heft-node-rig": "2.11.27",
64
+ "@types/heft-jest": "1.0.6",
65
+ "@types/jest": "^29.5.14",
66
+ "@types/node": "^20.14.9",
67
+ "@typescript-eslint/eslint-plugin": "^8.52.0",
68
+ "@typescript-eslint/parser": "^8.52.0",
69
+ "eslint": "^9.39.2",
70
+ "eslint-plugin-import": "^2.32.0",
71
+ "eslint-plugin-n": "^17.23.1",
72
+ "eslint-plugin-node": "^11.1.0",
73
+ "eslint-plugin-promise": "^7.2.1",
74
+ "eslint-plugin-tsdoc": "~0.5.2",
75
+ "jest": "^29.7.0",
76
+ "rimraf": "^6.1.2",
77
+ "ts-jest": "^29.4.6",
78
+ "ts-node": "^10.9.2",
79
+ "typescript": "5.9.3"
80
+ },
81
+ "peerDependencies": {
82
+ "@fgv/ts-utils": "workspace:*",
83
+ "@fgv/ts-extras": "workspace:*",
84
+ "@fgv/ts-json-base": "workspace:*"
85
+ }
86
+ }
@@ -0,0 +1,3 @@
1
+ Caching build output folders: dist, lib, temp, .rush/temp/operation/build
2
+ Successfully set cache entry.
3
+ Cache key: 5d207610a84e494acaefe7ed13447cda74ddf7da
@@ -0,0 +1,9 @@
1
+ Invoking: heft build --clean
2
+ ---- build started ----
3
+ [build:typescript] The TypeScript compiler version 5.9.3 is newer than the latest version that was tested with Heft (5.8); it may not work correctly.
4
+ [build:typescript] Using TypeScript version 5.9.3
5
+ [build:lint] Using ESLint version 9.39.4
6
+ [build:api-extractor] Using API Extractor version 7.58.7
7
+ [build:api-extractor] Analysis will use the bundled TypeScript version 5.9.3
8
+ ---- build finished (2.731s) ----
9
+ -------------------- Finished (2.732s) --------------------
package/src/index.ts ADDED
@@ -0,0 +1,50 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ /**
24
+ * `@fgv/ts-extras-mcp` — a Result-integration boundary over `@modelcontextprotocol/sdk` that
25
+ * connects to MCP (Model Context Protocol) servers, discovers their tools, and adapts each into
26
+ * an `AiAssist.IAiClientTool` so it drops directly into `AiAssist.executeClientToolTurn` —
27
+ * making any MCP server's tools callable across all four cloud providers with no per-provider work.
28
+ *
29
+ * Mirrors the discipline of `@fgv/ts-extras-webauthn` / `@fgv/ts-extras-transformers`: thin
30
+ * `Result<T>` conversion over a well-maintained upstream SDK, with no opinionated orchestration
31
+ * above the boundary.
32
+ *
33
+ * **In scope (slice 1, Node):** transport factories (`createStdioTransport`,
34
+ * `createHttpTransport`), session lifecycle (`connectMcpSession`, `closeMcpSession`), tool
35
+ * discovery + invocation (`listMcpTools`, `callMcpTool`), and the headline adapter
36
+ * (`adaptMcpTools`) which gracefully degrades on tools whose `inputSchema` is outside the
37
+ * supported JSON Schema subset (surfacing them on `skipped` and warning NOISILY).
38
+ *
39
+ * **Explicitly NOT in scope (deferred — see README / docs/FUTURE.md):**
40
+ * - Browser sibling `@fgv/ts-web-extras-mcp`
41
+ * - MCP resources / prompts / sampling features
42
+ * - OAuth / managed auth (static headers only at v0.1)
43
+ * - Multimodal tool-result passthrough (text-block projection only)
44
+ * - Cross-server tool-name namespacing (duplicate names already fail loudly in
45
+ * `executeClientToolTurn`)
46
+ *
47
+ * @packageDocumentation
48
+ */
49
+
50
+ export * from './packlets/mcp';
@@ -0,0 +1,152 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ /**
24
+ * The headline adapter — discovers an MCP server's tools and adapts each into an
25
+ * `AiAssist.IAiClientTool`, gracefully degrading (Constraint 1) on any tool whose `inputSchema`
26
+ * is outside the JSON Schema subset that `JsonSchema.fromJson` supports.
27
+ * @packageDocumentation
28
+ */
29
+
30
+ import { type Result, succeed } from '@fgv/ts-utils';
31
+ import { AiAssist } from '@fgv/ts-extras';
32
+ import { Converters, JsonSchema, type JsonValue } from '@fgv/ts-json-base';
33
+
34
+ import {
35
+ type IAdaptMcpToolsOptions,
36
+ type IAdaptMcpToolsResult,
37
+ type IMcpSession,
38
+ type IMcpSkippedTool,
39
+ type IMcpToolDescriptor
40
+ } from './model';
41
+ import { callMcpTool, listMcpTools } from './operations';
42
+
43
+ /**
44
+ * Per-tool adaptation outcome: either an adapted client tool, or a structurally-surfaced skip.
45
+ * `adaptMcpTools` never short-circuits on a skip — degradation is structural, not a failure.
46
+ */
47
+ type IAdaptOutcome =
48
+ | { readonly kind: 'tool'; readonly tool: AiAssist.IAiClientTool }
49
+ | { readonly kind: 'skipped'; readonly skipped: IMcpSkippedTool };
50
+
51
+ /**
52
+ * Builds the `execute` callback for an adapted MCP tool. Args arrive already validated against
53
+ * the tool's `parametersSchema` by `executeClientToolTurn`; here we narrow to a `JsonObject`
54
+ * (MCP arguments are always an object) and forward to {@link callMcpTool}, returning the
55
+ * projected text content. A tool error surfaces as a `Failure` (never swallowed).
56
+ */
57
+ function _makeExecute(session: IMcpSession, name: string): (args: unknown) => Promise<Result<unknown>> {
58
+ return async (args: unknown): Promise<Result<unknown>> => {
59
+ const objResult = Converters.jsonObject
60
+ .convert(args)
61
+ .withErrorFormat((msg) => `tool '${name}': arguments must be a JSON object: ${msg}`);
62
+ if (objResult.isFailure()) {
63
+ return objResult;
64
+ }
65
+ return (await callMcpTool(session, name, objResult.value)).onSuccess((called) => succeed(called.content));
66
+ };
67
+ }
68
+
69
+ /**
70
+ * Adapts a single discovered tool. Returns a `skipped` outcome (never a failure) when the
71
+ * tool's `inputSchema` is not a JSON object or is outside the `JsonSchema.fromJson` subset.
72
+ */
73
+ function _adaptOne(session: IMcpSession, descriptor: IMcpToolDescriptor): IAdaptOutcome {
74
+ const { name, description, inputSchema } = descriptor;
75
+
76
+ const skip = (reason: string, schema: JsonValue): IAdaptOutcome => ({
77
+ kind: 'skipped',
78
+ skipped: { name, reason, schema }
79
+ });
80
+
81
+ const asObject = Converters.jsonObject.convert(inputSchema);
82
+ if (asObject.isFailure()) {
83
+ return skip(`inputSchema is not a JSON object (${asObject.message})`, inputSchema);
84
+ }
85
+
86
+ const schemaResult = JsonSchema.fromJson(asObject.value);
87
+ if (schemaResult.isFailure()) {
88
+ return skip(schemaResult.message, inputSchema);
89
+ }
90
+
91
+ const config: AiAssist.IAiClientToolConfig = {
92
+ type: 'client_tool',
93
+ name,
94
+ description: description ?? name,
95
+ parametersSchema: schemaResult.value
96
+ };
97
+ return {
98
+ kind: 'tool',
99
+ tool: { config, execute: _makeExecute(session, name) }
100
+ };
101
+ }
102
+
103
+ /**
104
+ * Discovers an MCP server's tools and adapts each into an `AiAssist.IAiClientTool` that drops
105
+ * directly into `AiAssist.executeClientToolTurn`.
106
+ *
107
+ * @remarks
108
+ * **Constraint 1 — graceful degradation with NOISY warnings.** A tool whose `inputSchema` is
109
+ * outside the JSON Schema subset supported by `JsonSchema.fromJson` is NOT adapted (the model
110
+ * must never be offered a tool whose args we can't validate). Instead it is:
111
+ * 1. excluded from {@link IAdaptMcpToolsResult.tools};
112
+ * 2. surfaced structurally on {@link IAdaptMcpToolsResult.skipped} with the tool name, the
113
+ * JSON-pointer reason, and the raw failing schema; and
114
+ * 3. logged as a NOISY `warning` (name + reason + raw schema) when an `options.logger` is
115
+ * supplied — so pointing this at a new server immediately reveals every subset feature to
116
+ * extend, with the schema in hand.
117
+ *
118
+ * The whole catalog never fails on a single bad schema; the only failure mode is an upstream
119
+ * `listMcpTools` error.
120
+ *
121
+ * @param session - A connected session from `connectMcpSession`.
122
+ * @param options - Optional logger for the NOISY skip warnings.
123
+ * @returns `Success` with `{ tools, skipped }`, or `Failure` only if tool discovery fails.
124
+ * @public
125
+ */
126
+ export async function adaptMcpTools(
127
+ session: IMcpSession,
128
+ options?: IAdaptMcpToolsOptions
129
+ ): Promise<Result<IAdaptMcpToolsResult>> {
130
+ return (await listMcpTools(session))
131
+ .onSuccess((descriptors) => {
132
+ const tools: AiAssist.IAiClientTool[] = [];
133
+ const skipped: IMcpSkippedTool[] = [];
134
+
135
+ for (const descriptor of descriptors) {
136
+ const outcome = _adaptOne(session, descriptor);
137
+ if (outcome.kind === 'tool') {
138
+ tools.push(outcome.tool);
139
+ } else {
140
+ skipped.push(outcome.skipped);
141
+ options?.logger?.warn(
142
+ `mcp: skipping tool '${outcome.skipped.name}': inputSchema is outside the supported ` +
143
+ `JSON Schema subset: ${outcome.skipped.reason}. ` +
144
+ `Raw schema: ${JSON.stringify(outcome.skipped.schema)}`
145
+ );
146
+ }
147
+ }
148
+
149
+ return succeed<IAdaptMcpToolsResult>({ tools, skipped });
150
+ })
151
+ .withErrorFormat((msg) => `adaptMcpTools: ${msg}`);
152
+ }
@@ -0,0 +1,34 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ /**
24
+ * Public surface of the MCP packlet.
25
+ * @packageDocumentation
26
+ */
27
+
28
+ // `export *` (rather than named type-only re-exports) emits a runtime re-export of the
29
+ // types-only module so it participates in coverage as a loaded (zero-statement) module.
30
+ export * from './model';
31
+ export { createHttpTransport, createStdioTransport } from './transports';
32
+ export { closeMcpSession, connectMcpSession } from './session';
33
+ export { callMcpTool, listMcpTools } from './operations';
34
+ export { adaptMcpTools } from './adapter';
@@ -0,0 +1,204 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ /**
24
+ * Public types for the MCP → ai-assist client-tools boundary.
25
+ * @packageDocumentation
26
+ */
27
+
28
+ import { type Logging } from '@fgv/ts-utils';
29
+ import { type AiAssist } from '@fgv/ts-extras';
30
+ import { type JsonValue } from '@fgv/ts-json-base';
31
+
32
+ // ============================================================================
33
+ // Transport
34
+ // ============================================================================
35
+
36
+ /**
37
+ * Parameters for {@link createStdioTransport}. The transport spawns `command` as a
38
+ * subprocess and speaks MCP over its stdin/stdout.
39
+ *
40
+ * @remarks
41
+ * **Security:** stdio transport executes a consumer-supplied command. Treat `command`/`args`
42
+ * as a trust boundary — never source them from untrusted input. See the package README.
43
+ *
44
+ * @public
45
+ */
46
+ export interface IMcpStdioTransportParams {
47
+ /** Executable to spawn (e.g. `'npx'`, `'node'`, an absolute path). */
48
+ readonly command: string;
49
+ /** Arguments passed to the command. */
50
+ readonly args?: ReadonlyArray<string>;
51
+ /** Environment variables for the spawned process. When omitted, the SDK's safe default set is used. */
52
+ readonly env?: Record<string, string>;
53
+ /** Working directory for the spawned process. */
54
+ readonly cwd?: string;
55
+ }
56
+
57
+ /**
58
+ * Parameters for {@link createHttpTransport}. The transport connects to a Streamable-HTTP MCP
59
+ * endpoint.
60
+ * @public
61
+ */
62
+ export interface IMcpHttpTransportParams {
63
+ /** Absolute `http`/`https` URL of the MCP server endpoint. */
64
+ readonly url: string;
65
+ /** Optional static headers (e.g. an `Authorization` bearer token). OAuth/managed auth is out of scope at v0.1. */
66
+ readonly headers?: Record<string, string>;
67
+ }
68
+
69
+ /**
70
+ * Opaque handle to an MCP transport produced by {@link createStdioTransport} or
71
+ * {@link createHttpTransport}. Hand it to {@link connectMcpSession}; do not construct directly.
72
+ * @public
73
+ */
74
+ export interface IMcpTransport {
75
+ /** Which transport kind this handle wraps. */
76
+ readonly transportKind: 'stdio' | 'http';
77
+ }
78
+
79
+ // ============================================================================
80
+ // Session
81
+ // ============================================================================
82
+
83
+ /**
84
+ * Parameters for {@link connectMcpSession}.
85
+ * @public
86
+ */
87
+ export interface IConnectMcpSessionParams {
88
+ /** A transport produced by {@link createStdioTransport} / {@link createHttpTransport}. */
89
+ readonly transport: IMcpTransport;
90
+ /** Client name advertised to the server during the initialize handshake. Default `'@fgv/ts-extras-mcp'`. */
91
+ readonly clientName?: string;
92
+ /** Client version advertised to the server. Default the package version. */
93
+ readonly clientVersion?: string;
94
+ /** Optional logger for connection diagnostics. */
95
+ readonly logger?: Logging.ILogger;
96
+ }
97
+
98
+ /**
99
+ * Server identity reported during the MCP initialize handshake.
100
+ * @public
101
+ */
102
+ export interface IMcpServerInfo {
103
+ /** Server-advertised name. */
104
+ readonly name: string;
105
+ /** Server-advertised version. */
106
+ readonly version: string;
107
+ }
108
+
109
+ /**
110
+ * Opaque handle to a connected MCP session. Pass it to {@link listMcpTools},
111
+ * {@link callMcpTool}, {@link adaptMcpTools}, and {@link closeMcpSession}.
112
+ * @public
113
+ */
114
+ export interface IMcpSession {
115
+ /** Client name advertised during the handshake. */
116
+ readonly clientName: string;
117
+ /** Client version advertised during the handshake. */
118
+ readonly clientVersion: string;
119
+ /** Server identity reported by the handshake, when the server provided one. */
120
+ readonly serverInfo: IMcpServerInfo | undefined;
121
+ }
122
+
123
+ // ============================================================================
124
+ // Tool discovery + invocation
125
+ // ============================================================================
126
+
127
+ /**
128
+ * A tool descriptor discovered from an MCP server via {@link listMcpTools}.
129
+ * @public
130
+ */
131
+ export interface IMcpToolDescriptor {
132
+ /** Tool name (unique within a server). */
133
+ readonly name: string;
134
+ /** Human-readable description, when the server provided one. */
135
+ readonly description: string | undefined;
136
+ /**
137
+ * The tool's declared input schema as raw JSON. Per the MCP spec this is normally a JSON
138
+ * Schema object; carried verbatim so {@link adaptMcpTools} can run it through
139
+ * `JsonSchema.fromJson` (and surface it on {@link IMcpSkippedTool} when it is outside the
140
+ * supported subset).
141
+ */
142
+ readonly inputSchema: JsonValue;
143
+ }
144
+
145
+ /**
146
+ * Successful projection of an MCP `CallToolResult` produced by {@link callMcpTool}.
147
+ *
148
+ * @remarks
149
+ * `content` is the text concatenation of the result's `text` blocks; non-text blocks
150
+ * (image / audio / resource) are projected to a one-line `[<type> block]` summary
151
+ * (multimodal passthrough is out of scope at v0.1). A result with `isError: true` is mapped
152
+ * to `Result.fail(content)` rather than returned here, so it is never silently swallowed.
153
+ *
154
+ * @public
155
+ */
156
+ export interface IMcpToolCallResult {
157
+ /** The projected text content of the tool result. */
158
+ readonly content: string;
159
+ }
160
+
161
+ // ============================================================================
162
+ // Adapter (Constraint 1)
163
+ // ============================================================================
164
+
165
+ /**
166
+ * A tool that was discovered but could NOT be adapted into an `AiAssist.IAiClientTool`,
167
+ * because its `inputSchema` is outside the JSON Schema subset supported by
168
+ * `JsonSchema.fromJson`. Surfaced structurally so callers/the probe can enumerate exactly which
169
+ * subset features a server needs (with the raw schema in hand to extend `fromJson` later).
170
+ * @public
171
+ */
172
+ export interface IMcpSkippedTool {
173
+ /** The tool's name. */
174
+ readonly name: string;
175
+ /** Why the tool was skipped — the JSON-pointer reason from `JsonSchema.fromJson`, or a structural reason. */
176
+ readonly reason: string;
177
+ /** The raw failing input schema, verbatim, in hand for additively widening `JsonSchema.fromJson`. */
178
+ readonly schema: JsonValue;
179
+ }
180
+
181
+ /**
182
+ * Options for {@link adaptMcpTools}.
183
+ * @public
184
+ */
185
+ export interface IAdaptMcpToolsOptions {
186
+ /**
187
+ * Logger for the NOISY per-tool skip warnings. When a tool is skipped, a `warning` is emitted
188
+ * including the tool name, the JSON-pointer reason, and the raw failing schema. When omitted,
189
+ * skips are still surfaced structurally on {@link IAdaptMcpToolsResult.skipped}.
190
+ */
191
+ readonly logger?: Logging.ILogger;
192
+ }
193
+
194
+ /**
195
+ * The result of {@link adaptMcpTools}: cleanly-adapted client tools plus the structurally-surfaced
196
+ * set of tools that could not be adapted (graceful degradation, Constraint 1).
197
+ * @public
198
+ */
199
+ export interface IAdaptMcpToolsResult {
200
+ /** Tools adapted into `IAiClientTool` — safe to hand to `AiAssist.executeClientToolTurn`. */
201
+ readonly tools: ReadonlyArray<AiAssist.IAiClientTool>;
202
+ /** Tools excluded because their `inputSchema` is outside the supported JSON Schema subset. */
203
+ readonly skipped: ReadonlyArray<IMcpSkippedTool>;
204
+ }
@@ -0,0 +1,138 @@
1
+ /*
2
+ * Copyright (c) 2026 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ /**
24
+ * Tool discovery (`listMcpTools`, paginated) and invocation (`callMcpTool`, with `CallToolResult`
25
+ * projection), converting the throwing SDK calls into `Result<T>`.
26
+ * @packageDocumentation
27
+ */
28
+
29
+ import { type Result, captureAsyncResult, fail, succeed } from '@fgv/ts-utils';
30
+ import { Converters, type JsonObject } from '@fgv/ts-json-base';
31
+
32
+ import { type IMcpSession, type IMcpToolCallResult, type IMcpToolDescriptor } from './model';
33
+ import { type ISdkContentBlock, type ISdkToolDescriptor } from './sdk';
34
+ import { McpSession } from './session';
35
+
36
+ /**
37
+ * Projects a single SDK tool descriptor into a public {@link IMcpToolDescriptor}. The
38
+ * `inputSchema` field is validated as a `JsonValue`; an absent/non-JSON schema becomes `null`
39
+ * (which {@link adaptMcpTools} then reports as un-adaptable rather than offering it to the model).
40
+ */
41
+ function _toDescriptor(tool: ISdkToolDescriptor): IMcpToolDescriptor {
42
+ return {
43
+ name: tool.name,
44
+ description: tool.description,
45
+ inputSchema: Converters.jsonValue.convert(tool.inputSchema).orDefault(null)
46
+ };
47
+ }
48
+
49
+ /**
50
+ * Projects the SDK `CallToolResult` content blocks to a single string: `text` blocks are
51
+ * concatenated; every other block type becomes a one-line `[<type> block]` summary.
52
+ */
53
+ function _projectContent(blocks: ReadonlyArray<ISdkContentBlock> | undefined): string {
54
+ if (blocks === undefined || blocks.length === 0) {
55
+ return '';
56
+ }
57
+ return blocks
58
+ .map((block) =>
59
+ block.type === 'text' && block.text !== undefined ? block.text : `[${block.type} block]`
60
+ )
61
+ .join('\n');
62
+ }
63
+
64
+ /**
65
+ * Lists every tool a connected MCP server advertises, following the SDK's `nextCursor`
66
+ * pagination until the full catalog is accumulated.
67
+ *
68
+ * @param session - A session from `connectMcpSession`.
69
+ * @returns `Success` with the full tool catalog, or `Failure` on a foreign handle or a
70
+ * transport/protocol error.
71
+ * @public
72
+ */
73
+ export async function listMcpTools(session: IMcpSession): Promise<Result<ReadonlyArray<IMcpToolDescriptor>>> {
74
+ const sessionResult = McpSession.fromHandle(session);
75
+ if (sessionResult.isFailure()) {
76
+ return fail(`listMcpTools: ${sessionResult.message}`);
77
+ }
78
+ const { client } = sessionResult.value;
79
+
80
+ const all: IMcpToolDescriptor[] = [];
81
+ let cursor: string | undefined;
82
+
83
+ // Cursor-paginated loop: fetch each page, accumulate, advance until nextCursor is absent.
84
+ do {
85
+ const pageResult = await captureAsyncResult(() =>
86
+ client.listTools(cursor !== undefined ? { cursor } : undefined)
87
+ ).withErrorFormat((msg) => `listMcpTools: ${msg}`);
88
+ if (pageResult.isFailure()) {
89
+ return fail(pageResult.message);
90
+ }
91
+ for (const tool of pageResult.value.tools) {
92
+ all.push(_toDescriptor(tool));
93
+ }
94
+ cursor = pageResult.value.nextCursor;
95
+ } while (cursor !== undefined);
96
+
97
+ return succeed(all);
98
+ }
99
+
100
+ /**
101
+ * Calls a named tool on a connected MCP server.
102
+ *
103
+ * @remarks
104
+ * The SDK `CallToolResult` is projected to {@link IMcpToolCallResult} (text-block concatenation;
105
+ * non-text blocks summarized). A result flagged `isError: true` is mapped to `Result.fail` with
106
+ * the projected content — it is never swallowed, so `executeClientToolTurn` routes it back to the
107
+ * model as a provider-native error tool-result.
108
+ *
109
+ * @param session - A session from `connectMcpSession`.
110
+ * @param name - The tool name to invoke.
111
+ * @param args - The tool arguments (a JSON object).
112
+ * @returns `Success` with the projected content, or `Failure` on tool error / transport error /
113
+ * foreign handle.
114
+ * @public
115
+ */
116
+ export async function callMcpTool(
117
+ session: IMcpSession,
118
+ name: string,
119
+ args: JsonObject
120
+ ): Promise<Result<IMcpToolCallResult>> {
121
+ const sessionResult = McpSession.fromHandle(session);
122
+ if (sessionResult.isFailure()) {
123
+ return fail(`callMcpTool: ${sessionResult.message}`);
124
+ }
125
+ // The `withErrorFormat` wraps only transport/throw failures (it transforms the failure flowing
126
+ // out of `captureAsyncResult`); the `isError` failure created in the later `onSuccess` is
127
+ // downstream and stays clean, so the model-facing tool-error text is the server's verbatim
128
+ // content rather than a doubly-prefixed message.
129
+ return captureAsyncResult(() => sessionResult.value.client.callTool({ name, arguments: args }))
130
+ .withErrorFormat((msg) => `callMcpTool '${name}': ${msg}`)
131
+ .onSuccess((raw): Result<IMcpToolCallResult> => {
132
+ const content = _projectContent(raw.content);
133
+ if (raw.isError === true) {
134
+ return fail(content.length > 0 ? content : `tool '${name}' reported an error`);
135
+ }
136
+ return succeed({ content });
137
+ });
138
+ }