@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.
- package/.rush/temp/5d207610a84e494acaefe7ed13447cda74ddf7da.tar.log +90 -0
- package/.rush/temp/chunked-rush-logs/ts-extras-mcp.build.chunks.jsonl +9 -0
- package/.rush/temp/operation/build/all.log +9 -0
- package/.rush/temp/operation/build/log-chunks.jsonl +9 -0
- package/.rush/temp/operation/build/state.json +3 -0
- package/.rush/temp/shrinkwrap-deps.json +734 -0
- package/CHANGELOG.json +4 -0
- package/README.md +133 -0
- package/config/api-extractor.json +38 -0
- package/config/jest.config.json +13 -0
- package/config/rig.json +6 -0
- package/dist/index.js +49 -0
- package/dist/index.js.map +1 -0
- package/dist/packlets/mcp/adapter.js +122 -0
- package/dist/packlets/mcp/adapter.js.map +1 -0
- package/dist/packlets/mcp/index.js +33 -0
- package/dist/packlets/mcp/index.js.map +1 -0
- package/dist/packlets/mcp/model.js +23 -0
- package/dist/packlets/mcp/model.js.map +1 -0
- package/dist/packlets/mcp/operations.js +119 -0
- package/dist/packlets/mcp/operations.js.map +1 -0
- package/dist/packlets/mcp/sdk.js +67 -0
- package/dist/packlets/mcp/sdk.js.map +1 -0
- package/dist/packlets/mcp/session.js +109 -0
- package/dist/packlets/mcp/session.js.map +1 -0
- package/dist/packlets/mcp/transports.js +96 -0
- package/dist/packlets/mcp/transports.js.map +1 -0
- package/dist/test/unit/endToEnd.test.js +220 -0
- package/dist/test/unit/endToEnd.test.js.map +1 -0
- package/dist/test/unit/index.test.js +41 -0
- package/dist/test/unit/index.test.js.map +1 -0
- package/dist/test/unit/mcp.test.js +381 -0
- package/dist/test/unit/mcp.test.js.map +1 -0
- package/dist/test/unit/sdk.test.js +68 -0
- package/dist/test/unit/sdk.test.js.map +1 -0
- package/dist/ts-extras-mcp.d.ts +290 -0
- package/dist/tsdoc-metadata.json +11 -0
- package/eslint.config.js +15 -0
- package/etc/ts-extras-mcp.api.md +104 -0
- package/lib/index.d.ts +28 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +65 -0
- package/lib/index.js.map +1 -0
- package/lib/packlets/mcp/adapter.d.ts +33 -0
- package/lib/packlets/mcp/adapter.d.ts.map +1 -0
- package/lib/packlets/mcp/adapter.js +125 -0
- package/lib/packlets/mcp/adapter.js.map +1 -0
- package/lib/packlets/mcp/index.d.ts +10 -0
- package/lib/packlets/mcp/index.d.ts.map +1 -0
- package/lib/packlets/mcp/index.js +57 -0
- package/lib/packlets/mcp/index.js.map +1 -0
- package/lib/packlets/mcp/model.d.ts +155 -0
- package/lib/packlets/mcp/model.d.ts.map +1 -0
- package/lib/packlets/mcp/model.js +24 -0
- package/lib/packlets/mcp/model.js.map +1 -0
- package/lib/packlets/mcp/operations.d.ts +36 -0
- package/lib/packlets/mcp/operations.d.ts.map +1 -0
- package/lib/packlets/mcp/operations.js +123 -0
- package/lib/packlets/mcp/operations.js.map +1 -0
- package/lib/packlets/mcp/sdk.d.ts +91 -0
- package/lib/packlets/mcp/sdk.d.ts.map +1 -0
- package/lib/packlets/mcp/sdk.js +72 -0
- package/lib/packlets/mcp/sdk.js.map +1 -0
- package/lib/packlets/mcp/session.d.ts +43 -0
- package/lib/packlets/mcp/session.d.ts.map +1 -0
- package/lib/packlets/mcp/session.js +115 -0
- package/lib/packlets/mcp/session.js.map +1 -0
- package/lib/packlets/mcp/transports.d.ts +49 -0
- package/lib/packlets/mcp/transports.d.ts.map +1 -0
- package/lib/packlets/mcp/transports.js +102 -0
- package/lib/packlets/mcp/transports.js.map +1 -0
- package/lib/test/unit/endToEnd.test.d.ts +13 -0
- package/lib/test/unit/endToEnd.test.d.ts.map +1 -0
- package/lib/test/unit/endToEnd.test.js +222 -0
- package/lib/test/unit/endToEnd.test.js.map +1 -0
- package/lib/test/unit/index.test.d.ts +2 -0
- package/lib/test/unit/index.test.d.ts.map +1 -0
- package/lib/test/unit/index.test.js +76 -0
- package/lib/test/unit/index.test.js.map +1 -0
- package/lib/test/unit/mcp.test.d.ts +2 -0
- package/lib/test/unit/mcp.test.d.ts.map +1 -0
- package/lib/test/unit/mcp.test.js +416 -0
- package/lib/test/unit/mcp.test.js.map +1 -0
- package/lib/test/unit/sdk.test.d.ts +2 -0
- package/lib/test/unit/sdk.test.d.ts.map +1 -0
- package/lib/test/unit/sdk.test.js +70 -0
- package/lib/test/unit/sdk.test.js.map +1 -0
- package/package.json +86 -0
- package/rush-logs/ts-extras-mcp.build.cache.log +3 -0
- package/rush-logs/ts-extras-mcp.build.log +9 -0
- package/src/index.ts +50 -0
- package/src/packlets/mcp/adapter.ts +152 -0
- package/src/packlets/mcp/index.ts +34 -0
- package/src/packlets/mcp/model.ts +204 -0
- package/src/packlets/mcp/operations.ts +138 -0
- package/src/packlets/mcp/sdk.ts +148 -0
- package/src/packlets/mcp/session.ts +137 -0
- package/src/packlets/mcp/transports.ts +111 -0
- package/src/test/unit/endToEnd.test.ts +254 -0
- package/src/test/unit/index.test.ts +43 -0
- package/src/test/unit/mcp.test.ts +473 -0
- package/src/test/unit/sdk.test.ts +73 -0
- package/temp/build/lint/_eslint-5eVG3S6w.json +54 -0
- package/temp/build/typescript/ts_8nwakTlr.json +1 -0
- package/temp/ts-extras-mcp.api.json +1662 -0
- package/temp/ts-extras-mcp.api.md +104 -0
- package/tsconfig.json +12 -0
package/CHANGELOG.json
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# @fgv/ts-extras-mcp
|
|
2
|
+
|
|
3
|
+
Result-integration boundary over [`@modelcontextprotocol/sdk`](https://github.com/modelcontextprotocol/typescript-sdk)
|
|
4
|
+
for Node consumers. Connect to MCP (Model Context Protocol) servers, discover their tools, and
|
|
5
|
+
**adapt each into an `AiAssist.IAiClientTool`** from
|
|
6
|
+
[`@fgv/ts-extras`](../ts-extras) so it drops directly into `AiAssist.executeClientToolTurn`.
|
|
7
|
+
|
|
8
|
+
Net effect: any MCP server's tools become callable across all four cloud providers (Anthropic,
|
|
9
|
+
OpenAI, Gemini, xAI) with no per-provider work.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## What this is
|
|
14
|
+
|
|
15
|
+
A thin facade that wraps `@modelcontextprotocol/sdk` calls in `Result<T>` from `@fgv/ts-utils`,
|
|
16
|
+
mirroring the discipline established by
|
|
17
|
+
[`@fgv/ts-extras-webauthn`](../ts-extras-webauthn) and
|
|
18
|
+
[`@fgv/ts-extras-transformers`](../ts-extras-transformers): `captureAsyncResult` conversion of the
|
|
19
|
+
upstream throw-based API into `Result<T>`, plus exactly one piece of glue — converting MCP tool
|
|
20
|
+
descriptors into `IAiClientTool[]`. **No opinionated orchestration above the boundary.**
|
|
21
|
+
|
|
22
|
+
All `@modelcontextprotocol/sdk` imports live in a single file (`src/packlets/mcp/sdk.ts`) so the
|
|
23
|
+
announced SDK v2 client-package rename is a one-file change.
|
|
24
|
+
|
|
25
|
+
## Explicitly NOT in scope
|
|
26
|
+
|
|
27
|
+
These were considered and deferred — use `@modelcontextprotocol/sdk` directly (with
|
|
28
|
+
`captureAsyncResult` for your own Result wrapping) for any of them:
|
|
29
|
+
|
|
30
|
+
- **Browser sibling** (`@fgv/ts-web-extras-mcp`) — Node-only at v0.1.
|
|
31
|
+
- **MCP resources / prompts / sampling** — tool discovery + invocation only.
|
|
32
|
+
- **OAuth / managed auth** — static headers only (`createHttpTransport({ headers })`).
|
|
33
|
+
- **Multimodal tool-result passthrough** — non-text content blocks are projected to a one-line
|
|
34
|
+
`[<type> block]` summary.
|
|
35
|
+
- **Cross-server tool-name namespacing** — duplicate tool names already fail loudly in
|
|
36
|
+
`AiAssist.executeClientToolTurn`.
|
|
37
|
+
- **MCP server orchestration / lifecycle management beyond a single session.**
|
|
38
|
+
|
|
39
|
+
See [`docs/FUTURE.md`](../../docs/FUTURE.md) for the tracked follow-ups.
|
|
40
|
+
|
|
41
|
+
## The primitives
|
|
42
|
+
|
|
43
|
+
| Function | Return |
|
|
44
|
+
|---|---|
|
|
45
|
+
| `createStdioTransport({ command, args?, env?, cwd? })` | `Result<IMcpTransport>` |
|
|
46
|
+
| `createHttpTransport({ url, headers? })` | `Result<IMcpTransport>` |
|
|
47
|
+
| `connectMcpSession({ transport, clientName?, clientVersion?, logger? })` | `Promise<Result<IMcpSession>>` |
|
|
48
|
+
| `closeMcpSession(session)` | `Promise<Result<true>>` |
|
|
49
|
+
| `listMcpTools(session)` | `Promise<Result<ReadonlyArray<IMcpToolDescriptor>>>` |
|
|
50
|
+
| `callMcpTool(session, name, args)` | `Promise<Result<IMcpToolCallResult>>` |
|
|
51
|
+
| `adaptMcpTools(session, { logger? })` | `Promise<Result<IAdaptMcpToolsResult>>` |
|
|
52
|
+
|
|
53
|
+
## Usage
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
import {
|
|
57
|
+
createStdioTransport,
|
|
58
|
+
connectMcpSession,
|
|
59
|
+
adaptMcpTools,
|
|
60
|
+
closeMcpSession
|
|
61
|
+
} from '@fgv/ts-extras-mcp';
|
|
62
|
+
import { AiAssist } from '@fgv/ts-extras';
|
|
63
|
+
|
|
64
|
+
// 1. Connect to an MCP server (stdio spawns a subprocess; see the security note below).
|
|
65
|
+
const transport = createStdioTransport({
|
|
66
|
+
command: 'npx',
|
|
67
|
+
args: ['-y', '@modelcontextprotocol/server-everything']
|
|
68
|
+
}).orThrow();
|
|
69
|
+
|
|
70
|
+
const sessionResult = await connectMcpSession({ transport });
|
|
71
|
+
if (sessionResult.isFailure()) {
|
|
72
|
+
// connection / handshake failed
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const session = sessionResult.value;
|
|
76
|
+
|
|
77
|
+
// 2. Adapt the server's tools into ai-assist client tools.
|
|
78
|
+
const adaptResult = (await adaptMcpTools(session, { logger })).orThrow();
|
|
79
|
+
|
|
80
|
+
// adaptResult.tools → ReadonlyArray<AiAssist.IAiClientTool>, ready to hand to the model
|
|
81
|
+
// adaptResult.skipped → tools whose inputSchema is outside the supported JSON Schema subset
|
|
82
|
+
// (each carries the failing schema + a JSON-pointer reason)
|
|
83
|
+
|
|
84
|
+
// 3. Drop the adapted tools straight into the client-tools turn loop.
|
|
85
|
+
const turn = AiAssist.executeClientToolTurn({
|
|
86
|
+
descriptor,
|
|
87
|
+
apiKey,
|
|
88
|
+
prompt,
|
|
89
|
+
clientTools: adaptResult.tools
|
|
90
|
+
}).orThrow();
|
|
91
|
+
|
|
92
|
+
// ... iterate turn.events / await turn.nextTurn ...
|
|
93
|
+
|
|
94
|
+
await closeMcpSession(session);
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### Graceful degradation (load-bearing)
|
|
98
|
+
|
|
99
|
+
`adaptMcpTools` **never fails the whole catalog because one tool's schema is unsupported.** When a
|
|
100
|
+
discovered tool's `inputSchema` is outside the JSON Schema subset that
|
|
101
|
+
[`JsonSchema.fromJson`](../ts-json-base) supports, that one tool is excluded from `tools` (the
|
|
102
|
+
model is never offered a tool whose arguments we can't validate), surfaced structurally on
|
|
103
|
+
`skipped` (with the tool name, the JSON-pointer reason, and the raw failing schema), and — when a
|
|
104
|
+
`logger` is supplied — logged as a NOISY `warning` carrying all three. Point this at a new server
|
|
105
|
+
and you immediately see every schema feature that needs additive support in `JsonSchema.fromJson`.
|
|
106
|
+
|
|
107
|
+
## Compatibility probe
|
|
108
|
+
|
|
109
|
+
The `samples/testbed` `mcp-probe` scenario points this package at any MCP server and prints a
|
|
110
|
+
compatibility report (adapted vs. skipped tools, with the failing schema + reason for each skip).
|
|
111
|
+
Run it without wiring the server into an application:
|
|
112
|
+
|
|
113
|
+
```sh
|
|
114
|
+
# stdio server:
|
|
115
|
+
MCP_PROBE_COMMAND=npx MCP_PROBE_ARGS="-y @modelcontextprotocol/server-everything" \
|
|
116
|
+
node samples/testbed/bin/testbed.js --scenario mcp-probe
|
|
117
|
+
|
|
118
|
+
# HTTP server:
|
|
119
|
+
MCP_PROBE_URL=http://localhost:3001/mcp MCP_PROBE_HEADERS="authorization=Bearer xyz" \
|
|
120
|
+
node samples/testbed/bin/testbed.js --scenario mcp-probe
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Security — stdio transport trust boundary
|
|
124
|
+
|
|
125
|
+
`createStdioTransport` spawns `command` (with `args`) as a **child process**. The command runs
|
|
126
|
+
with the privileges of the host process. **Never source the command, arguments, or environment
|
|
127
|
+
from untrusted input** — treat them with the same care as any shell-out. The HTTP transport
|
|
128
|
+
(`createHttpTransport`) does not spawn a process; supply credentials via static `headers`.
|
|
129
|
+
|
|
130
|
+
## Runtime requirements
|
|
131
|
+
|
|
132
|
+
- Node.js 20 LTS or later.
|
|
133
|
+
- `@modelcontextprotocol/sdk` `^1.29.0` (a direct dependency).
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
|
|
3
|
+
"projectFolder": "..",
|
|
4
|
+
"mainEntryPointFilePath": "<projectFolder>/lib/index.d.ts",
|
|
5
|
+
"bundledPackages": [],
|
|
6
|
+
"compiler": {},
|
|
7
|
+
"apiReport": {
|
|
8
|
+
"enabled": true
|
|
9
|
+
},
|
|
10
|
+
"docModel": {
|
|
11
|
+
"enabled": true
|
|
12
|
+
},
|
|
13
|
+
"dtsRollup": {
|
|
14
|
+
"enabled": true
|
|
15
|
+
},
|
|
16
|
+
"tsdocMetadata": {},
|
|
17
|
+
"messages": {
|
|
18
|
+
"compilerMessageReporting": {
|
|
19
|
+
"default": {
|
|
20
|
+
"logLevel": "warning"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"extractorMessageReporting": {
|
|
24
|
+
"default": {
|
|
25
|
+
"logLevel": "warning"
|
|
26
|
+
},
|
|
27
|
+
"ae-unresolved-link": {
|
|
28
|
+
"logLevel": "none",
|
|
29
|
+
"addToApiReportFile": true
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"tsdocMessageReporting": {
|
|
33
|
+
"default": {
|
|
34
|
+
"logLevel": "warning"
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "@rushstack/heft-node-rig/profiles/default/config/jest.config.json",
|
|
3
|
+
"coverageThreshold": {
|
|
4
|
+
"global": {
|
|
5
|
+
"branches": 100,
|
|
6
|
+
"functions": 100,
|
|
7
|
+
"lines": 100,
|
|
8
|
+
"statements": 100
|
|
9
|
+
}
|
|
10
|
+
},
|
|
11
|
+
"collectCoverage": true,
|
|
12
|
+
"coverageReporters": ["text", "lcov", "html"]
|
|
13
|
+
}
|
package/config/rig.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// The "rig.json" file directs tools to look for their config files in an external package.
|
|
2
|
+
// Documentation for this system: https://www.npmjs.com/package/@rushstack/rig-package
|
|
3
|
+
{
|
|
4
|
+
"$schema": "https://developer.microsoft.com/json-schemas/rig-package/rig.schema.json",
|
|
5
|
+
"rigPackageName": "@fgv/heft-dual-rig"
|
|
6
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
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
|
+
* `@fgv/ts-extras-mcp` — a Result-integration boundary over `@modelcontextprotocol/sdk` that
|
|
24
|
+
* connects to MCP (Model Context Protocol) servers, discovers their tools, and adapts each into
|
|
25
|
+
* an `AiAssist.IAiClientTool` so it drops directly into `AiAssist.executeClientToolTurn` —
|
|
26
|
+
* making any MCP server's tools callable across all four cloud providers with no per-provider work.
|
|
27
|
+
*
|
|
28
|
+
* Mirrors the discipline of `@fgv/ts-extras-webauthn` / `@fgv/ts-extras-transformers`: thin
|
|
29
|
+
* `Result<T>` conversion over a well-maintained upstream SDK, with no opinionated orchestration
|
|
30
|
+
* above the boundary.
|
|
31
|
+
*
|
|
32
|
+
* **In scope (slice 1, Node):** transport factories (`createStdioTransport`,
|
|
33
|
+
* `createHttpTransport`), session lifecycle (`connectMcpSession`, `closeMcpSession`), tool
|
|
34
|
+
* discovery + invocation (`listMcpTools`, `callMcpTool`), and the headline adapter
|
|
35
|
+
* (`adaptMcpTools`) which gracefully degrades on tools whose `inputSchema` is outside the
|
|
36
|
+
* supported JSON Schema subset (surfacing them on `skipped` and warning NOISILY).
|
|
37
|
+
*
|
|
38
|
+
* **Explicitly NOT in scope (deferred — see README / docs/FUTURE.md):**
|
|
39
|
+
* - Browser sibling `@fgv/ts-web-extras-mcp`
|
|
40
|
+
* - MCP resources / prompts / sampling features
|
|
41
|
+
* - OAuth / managed auth (static headers only at v0.1)
|
|
42
|
+
* - Multimodal tool-result passthrough (text-block projection only)
|
|
43
|
+
* - Cross-server tool-name namespacing (duplicate names already fail loudly in
|
|
44
|
+
* `executeClientToolTurn`)
|
|
45
|
+
*
|
|
46
|
+
* @packageDocumentation
|
|
47
|
+
*/
|
|
48
|
+
export * from './packlets/mcp';
|
|
49
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,cAAc,gBAAgB,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * `@fgv/ts-extras-mcp` — a Result-integration boundary over `@modelcontextprotocol/sdk` that\n * connects to MCP (Model Context Protocol) servers, discovers their tools, and adapts each into\n * an `AiAssist.IAiClientTool` so it drops directly into `AiAssist.executeClientToolTurn` —\n * making any MCP server's tools callable across all four cloud providers with no per-provider work.\n *\n * Mirrors the discipline of `@fgv/ts-extras-webauthn` / `@fgv/ts-extras-transformers`: thin\n * `Result<T>` conversion over a well-maintained upstream SDK, with no opinionated orchestration\n * above the boundary.\n *\n * **In scope (slice 1, Node):** transport factories (`createStdioTransport`,\n * `createHttpTransport`), session lifecycle (`connectMcpSession`, `closeMcpSession`), tool\n * discovery + invocation (`listMcpTools`, `callMcpTool`), and the headline adapter\n * (`adaptMcpTools`) which gracefully degrades on tools whose `inputSchema` is outside the\n * supported JSON Schema subset (surfacing them on `skipped` and warning NOISILY).\n *\n * **Explicitly NOT in scope (deferred — see README / docs/FUTURE.md):**\n * - Browser sibling `@fgv/ts-web-extras-mcp`\n * - MCP resources / prompts / sampling features\n * - OAuth / managed auth (static headers only at v0.1)\n * - Multimodal tool-result passthrough (text-block projection only)\n * - Cross-server tool-name namespacing (duplicate names already fail loudly in\n * `executeClientToolTurn`)\n *\n * @packageDocumentation\n */\n\nexport * from './packlets/mcp';\n"]}
|
|
@@ -0,0 +1,122 @@
|
|
|
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
|
+
* The headline adapter — discovers an MCP server's tools and adapts each into an
|
|
24
|
+
* `AiAssist.IAiClientTool`, gracefully degrading (Constraint 1) on any tool whose `inputSchema`
|
|
25
|
+
* is outside the JSON Schema subset that `JsonSchema.fromJson` supports.
|
|
26
|
+
* @packageDocumentation
|
|
27
|
+
*/
|
|
28
|
+
import { succeed } from '@fgv/ts-utils';
|
|
29
|
+
import { Converters, JsonSchema } from '@fgv/ts-json-base';
|
|
30
|
+
import { callMcpTool, listMcpTools } from './operations';
|
|
31
|
+
/**
|
|
32
|
+
* Builds the `execute` callback for an adapted MCP tool. Args arrive already validated against
|
|
33
|
+
* the tool's `parametersSchema` by `executeClientToolTurn`; here we narrow to a `JsonObject`
|
|
34
|
+
* (MCP arguments are always an object) and forward to {@link callMcpTool}, returning the
|
|
35
|
+
* projected text content. A tool error surfaces as a `Failure` (never swallowed).
|
|
36
|
+
*/
|
|
37
|
+
function _makeExecute(session, name) {
|
|
38
|
+
return async (args) => {
|
|
39
|
+
const objResult = Converters.jsonObject
|
|
40
|
+
.convert(args)
|
|
41
|
+
.withErrorFormat((msg) => `tool '${name}': arguments must be a JSON object: ${msg}`);
|
|
42
|
+
if (objResult.isFailure()) {
|
|
43
|
+
return objResult;
|
|
44
|
+
}
|
|
45
|
+
return (await callMcpTool(session, name, objResult.value)).onSuccess((called) => succeed(called.content));
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Adapts a single discovered tool. Returns a `skipped` outcome (never a failure) when the
|
|
50
|
+
* tool's `inputSchema` is not a JSON object or is outside the `JsonSchema.fromJson` subset.
|
|
51
|
+
*/
|
|
52
|
+
function _adaptOne(session, descriptor) {
|
|
53
|
+
const { name, description, inputSchema } = descriptor;
|
|
54
|
+
const skip = (reason, schema) => ({
|
|
55
|
+
kind: 'skipped',
|
|
56
|
+
skipped: { name, reason, schema }
|
|
57
|
+
});
|
|
58
|
+
const asObject = Converters.jsonObject.convert(inputSchema);
|
|
59
|
+
if (asObject.isFailure()) {
|
|
60
|
+
return skip(`inputSchema is not a JSON object (${asObject.message})`, inputSchema);
|
|
61
|
+
}
|
|
62
|
+
const schemaResult = JsonSchema.fromJson(asObject.value);
|
|
63
|
+
if (schemaResult.isFailure()) {
|
|
64
|
+
return skip(schemaResult.message, inputSchema);
|
|
65
|
+
}
|
|
66
|
+
const config = {
|
|
67
|
+
type: 'client_tool',
|
|
68
|
+
name,
|
|
69
|
+
description: description !== null && description !== void 0 ? description : name,
|
|
70
|
+
parametersSchema: schemaResult.value
|
|
71
|
+
};
|
|
72
|
+
return {
|
|
73
|
+
kind: 'tool',
|
|
74
|
+
tool: { config, execute: _makeExecute(session, name) }
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Discovers an MCP server's tools and adapts each into an `AiAssist.IAiClientTool` that drops
|
|
79
|
+
* directly into `AiAssist.executeClientToolTurn`.
|
|
80
|
+
*
|
|
81
|
+
* @remarks
|
|
82
|
+
* **Constraint 1 — graceful degradation with NOISY warnings.** A tool whose `inputSchema` is
|
|
83
|
+
* outside the JSON Schema subset supported by `JsonSchema.fromJson` is NOT adapted (the model
|
|
84
|
+
* must never be offered a tool whose args we can't validate). Instead it is:
|
|
85
|
+
* 1. excluded from {@link IAdaptMcpToolsResult.tools};
|
|
86
|
+
* 2. surfaced structurally on {@link IAdaptMcpToolsResult.skipped} with the tool name, the
|
|
87
|
+
* JSON-pointer reason, and the raw failing schema; and
|
|
88
|
+
* 3. logged as a NOISY `warning` (name + reason + raw schema) when an `options.logger` is
|
|
89
|
+
* supplied — so pointing this at a new server immediately reveals every subset feature to
|
|
90
|
+
* extend, with the schema in hand.
|
|
91
|
+
*
|
|
92
|
+
* The whole catalog never fails on a single bad schema; the only failure mode is an upstream
|
|
93
|
+
* `listMcpTools` error.
|
|
94
|
+
*
|
|
95
|
+
* @param session - A connected session from `connectMcpSession`.
|
|
96
|
+
* @param options - Optional logger for the NOISY skip warnings.
|
|
97
|
+
* @returns `Success` with `{ tools, skipped }`, or `Failure` only if tool discovery fails.
|
|
98
|
+
* @public
|
|
99
|
+
*/
|
|
100
|
+
export async function adaptMcpTools(session, options) {
|
|
101
|
+
return (await listMcpTools(session))
|
|
102
|
+
.onSuccess((descriptors) => {
|
|
103
|
+
var _a;
|
|
104
|
+
const tools = [];
|
|
105
|
+
const skipped = [];
|
|
106
|
+
for (const descriptor of descriptors) {
|
|
107
|
+
const outcome = _adaptOne(session, descriptor);
|
|
108
|
+
if (outcome.kind === 'tool') {
|
|
109
|
+
tools.push(outcome.tool);
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
skipped.push(outcome.skipped);
|
|
113
|
+
(_a = options === null || options === void 0 ? void 0 : options.logger) === null || _a === void 0 ? void 0 : _a.warn(`mcp: skipping tool '${outcome.skipped.name}': inputSchema is outside the supported ` +
|
|
114
|
+
`JSON Schema subset: ${outcome.skipped.reason}. ` +
|
|
115
|
+
`Raw schema: ${JSON.stringify(outcome.skipped.schema)}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return succeed({ tools, skipped });
|
|
119
|
+
})
|
|
120
|
+
.withErrorFormat((msg) => `adaptMcpTools: ${msg}`);
|
|
121
|
+
}
|
|
122
|
+
//# sourceMappingURL=adapter.js.map
|
|
@@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B,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;gBAC9B,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM,0CAAE,IAAI,CACnB,uBAAuB,OAAO,CAAC,OAAO,CAAC,IAAI,0CAA0C;oBACnF,uBAAuB,OAAO,CAAC,OAAO,CAAC,MAAM,IAAI;oBACjD,eAAe,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAC1D,CAAC;YACJ,CAAC;QACH,CAAC;QAED,OAAO,OAAO,CAAuB,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IAC3D,CAAC,CAAC;SACD,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,kBAAkB,GAAG,EAAE,CAAC,CAAC;AACvD,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * The headline adapter — discovers an MCP server's tools and adapts each into an\n * `AiAssist.IAiClientTool`, gracefully degrading (Constraint 1) on any tool whose `inputSchema`\n * is outside the JSON Schema subset that `JsonSchema.fromJson` supports.\n * @packageDocumentation\n */\n\nimport { type Result, succeed } from '@fgv/ts-utils';\nimport { AiAssist } from '@fgv/ts-extras';\nimport { Converters, JsonSchema, type JsonValue } from '@fgv/ts-json-base';\n\nimport {\n type IAdaptMcpToolsOptions,\n type IAdaptMcpToolsResult,\n type IMcpSession,\n type IMcpSkippedTool,\n type IMcpToolDescriptor\n} from './model';\nimport { callMcpTool, listMcpTools } from './operations';\n\n/**\n * Per-tool adaptation outcome: either an adapted client tool, or a structurally-surfaced skip.\n * `adaptMcpTools` never short-circuits on a skip — degradation is structural, not a failure.\n */\ntype IAdaptOutcome =\n | { readonly kind: 'tool'; readonly tool: AiAssist.IAiClientTool }\n | { readonly kind: 'skipped'; readonly skipped: IMcpSkippedTool };\n\n/**\n * Builds the `execute` callback for an adapted MCP tool. Args arrive already validated against\n * the tool's `parametersSchema` by `executeClientToolTurn`; here we narrow to a `JsonObject`\n * (MCP arguments are always an object) and forward to {@link callMcpTool}, returning the\n * projected text content. A tool error surfaces as a `Failure` (never swallowed).\n */\nfunction _makeExecute(session: IMcpSession, name: string): (args: unknown) => Promise<Result<unknown>> {\n return async (args: unknown): Promise<Result<unknown>> => {\n const objResult = Converters.jsonObject\n .convert(args)\n .withErrorFormat((msg) => `tool '${name}': arguments must be a JSON object: ${msg}`);\n if (objResult.isFailure()) {\n return objResult;\n }\n return (await callMcpTool(session, name, objResult.value)).onSuccess((called) => succeed(called.content));\n };\n}\n\n/**\n * Adapts a single discovered tool. Returns a `skipped` outcome (never a failure) when the\n * tool's `inputSchema` is not a JSON object or is outside the `JsonSchema.fromJson` subset.\n */\nfunction _adaptOne(session: IMcpSession, descriptor: IMcpToolDescriptor): IAdaptOutcome {\n const { name, description, inputSchema } = descriptor;\n\n const skip = (reason: string, schema: JsonValue): IAdaptOutcome => ({\n kind: 'skipped',\n skipped: { name, reason, schema }\n });\n\n const asObject = Converters.jsonObject.convert(inputSchema);\n if (asObject.isFailure()) {\n return skip(`inputSchema is not a JSON object (${asObject.message})`, inputSchema);\n }\n\n const schemaResult = JsonSchema.fromJson(asObject.value);\n if (schemaResult.isFailure()) {\n return skip(schemaResult.message, inputSchema);\n }\n\n const config: AiAssist.IAiClientToolConfig = {\n type: 'client_tool',\n name,\n description: description ?? name,\n parametersSchema: schemaResult.value\n };\n return {\n kind: 'tool',\n tool: { config, execute: _makeExecute(session, name) }\n };\n}\n\n/**\n * Discovers an MCP server's tools and adapts each into an `AiAssist.IAiClientTool` that drops\n * directly into `AiAssist.executeClientToolTurn`.\n *\n * @remarks\n * **Constraint 1 — graceful degradation with NOISY warnings.** A tool whose `inputSchema` is\n * outside the JSON Schema subset supported by `JsonSchema.fromJson` is NOT adapted (the model\n * must never be offered a tool whose args we can't validate). Instead it is:\n * 1. excluded from {@link IAdaptMcpToolsResult.tools};\n * 2. surfaced structurally on {@link IAdaptMcpToolsResult.skipped} with the tool name, the\n * JSON-pointer reason, and the raw failing schema; and\n * 3. logged as a NOISY `warning` (name + reason + raw schema) when an `options.logger` is\n * supplied — so pointing this at a new server immediately reveals every subset feature to\n * extend, with the schema in hand.\n *\n * The whole catalog never fails on a single bad schema; the only failure mode is an upstream\n * `listMcpTools` error.\n *\n * @param session - A connected session from `connectMcpSession`.\n * @param options - Optional logger for the NOISY skip warnings.\n * @returns `Success` with `{ tools, skipped }`, or `Failure` only if tool discovery fails.\n * @public\n */\nexport async function adaptMcpTools(\n session: IMcpSession,\n options?: IAdaptMcpToolsOptions\n): Promise<Result<IAdaptMcpToolsResult>> {\n return (await listMcpTools(session))\n .onSuccess((descriptors) => {\n const tools: AiAssist.IAiClientTool[] = [];\n const skipped: IMcpSkippedTool[] = [];\n\n for (const descriptor of descriptors) {\n const outcome = _adaptOne(session, descriptor);\n if (outcome.kind === 'tool') {\n tools.push(outcome.tool);\n } else {\n skipped.push(outcome.skipped);\n options?.logger?.warn(\n `mcp: skipping tool '${outcome.skipped.name}': inputSchema is outside the supported ` +\n `JSON Schema subset: ${outcome.skipped.reason}. ` +\n `Raw schema: ${JSON.stringify(outcome.skipped.schema)}`\n );\n }\n }\n\n return succeed<IAdaptMcpToolsResult>({ tools, skipped });\n })\n .withErrorFormat((msg) => `adaptMcpTools: ${msg}`);\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
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
|
+
* Public surface of the MCP packlet.
|
|
24
|
+
* @packageDocumentation
|
|
25
|
+
*/
|
|
26
|
+
// `export *` (rather than named type-only re-exports) emits a runtime re-export of the
|
|
27
|
+
// types-only module so it participates in coverage as a loaded (zero-statement) module.
|
|
28
|
+
export * from './model';
|
|
29
|
+
export { createHttpTransport, createStdioTransport } from './transports';
|
|
30
|
+
export { closeMcpSession, connectMcpSession } from './session';
|
|
31
|
+
export { callMcpTool, listMcpTools } from './operations';
|
|
32
|
+
export { adaptMcpTools } from './adapter';
|
|
33
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/mcp/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;GAGG;AAEH,uFAAuF;AACvF,wFAAwF;AACxF,cAAc,SAAS,CAAC;AACxB,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACzE,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Public surface of the MCP packlet.\n * @packageDocumentation\n */\n\n// `export *` (rather than named type-only re-exports) emits a runtime re-export of the\n// types-only module so it participates in coverage as a loaded (zero-statement) module.\nexport * from './model';\nexport { createHttpTransport, createStdioTransport } from './transports';\nexport { closeMcpSession, connectMcpSession } from './session';\nexport { callMcpTool, listMcpTools } from './operations';\nexport { adaptMcpTools } from './adapter';\n"]}
|
|
@@ -0,0 +1,23 @@
|
|
|
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
|
+
export {};
|
|
23
|
+
//# sourceMappingURL=model.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model.js","sourceRoot":"","sources":["../../../src/packlets/mcp/model.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Public types for the MCP → ai-assist client-tools boundary.\n * @packageDocumentation\n */\n\nimport { type Logging } from '@fgv/ts-utils';\nimport { type AiAssist } from '@fgv/ts-extras';\nimport { type JsonValue } from '@fgv/ts-json-base';\n\n// ============================================================================\n// Transport\n// ============================================================================\n\n/**\n * Parameters for {@link createStdioTransport}. The transport spawns `command` as a\n * subprocess and speaks MCP over its stdin/stdout.\n *\n * @remarks\n * **Security:** stdio transport executes a consumer-supplied command. Treat `command`/`args`\n * as a trust boundary — never source them from untrusted input. See the package README.\n *\n * @public\n */\nexport interface IMcpStdioTransportParams {\n /** Executable to spawn (e.g. `'npx'`, `'node'`, an absolute path). */\n readonly command: string;\n /** Arguments passed to the command. */\n readonly args?: ReadonlyArray<string>;\n /** Environment variables for the spawned process. When omitted, the SDK's safe default set is used. */\n readonly env?: Record<string, string>;\n /** Working directory for the spawned process. */\n readonly cwd?: string;\n}\n\n/**\n * Parameters for {@link createHttpTransport}. The transport connects to a Streamable-HTTP MCP\n * endpoint.\n * @public\n */\nexport interface IMcpHttpTransportParams {\n /** Absolute `http`/`https` URL of the MCP server endpoint. */\n readonly url: string;\n /** Optional static headers (e.g. an `Authorization` bearer token). OAuth/managed auth is out of scope at v0.1. */\n readonly headers?: Record<string, string>;\n}\n\n/**\n * Opaque handle to an MCP transport produced by {@link createStdioTransport} or\n * {@link createHttpTransport}. Hand it to {@link connectMcpSession}; do not construct directly.\n * @public\n */\nexport interface IMcpTransport {\n /** Which transport kind this handle wraps. */\n readonly transportKind: 'stdio' | 'http';\n}\n\n// ============================================================================\n// Session\n// ============================================================================\n\n/**\n * Parameters for {@link connectMcpSession}.\n * @public\n */\nexport interface IConnectMcpSessionParams {\n /** A transport produced by {@link createStdioTransport} / {@link createHttpTransport}. */\n readonly transport: IMcpTransport;\n /** Client name advertised to the server during the initialize handshake. Default `'@fgv/ts-extras-mcp'`. */\n readonly clientName?: string;\n /** Client version advertised to the server. Default the package version. */\n readonly clientVersion?: string;\n /** Optional logger for connection diagnostics. */\n readonly logger?: Logging.ILogger;\n}\n\n/**\n * Server identity reported during the MCP initialize handshake.\n * @public\n */\nexport interface IMcpServerInfo {\n /** Server-advertised name. */\n readonly name: string;\n /** Server-advertised version. */\n readonly version: string;\n}\n\n/**\n * Opaque handle to a connected MCP session. Pass it to {@link listMcpTools},\n * {@link callMcpTool}, {@link adaptMcpTools}, and {@link closeMcpSession}.\n * @public\n */\nexport interface IMcpSession {\n /** Client name advertised during the handshake. */\n readonly clientName: string;\n /** Client version advertised during the handshake. */\n readonly clientVersion: string;\n /** Server identity reported by the handshake, when the server provided one. */\n readonly serverInfo: IMcpServerInfo | undefined;\n}\n\n// ============================================================================\n// Tool discovery + invocation\n// ============================================================================\n\n/**\n * A tool descriptor discovered from an MCP server via {@link listMcpTools}.\n * @public\n */\nexport interface IMcpToolDescriptor {\n /** Tool name (unique within a server). */\n readonly name: string;\n /** Human-readable description, when the server provided one. */\n readonly description: string | undefined;\n /**\n * The tool's declared input schema as raw JSON. Per the MCP spec this is normally a JSON\n * Schema object; carried verbatim so {@link adaptMcpTools} can run it through\n * `JsonSchema.fromJson` (and surface it on {@link IMcpSkippedTool} when it is outside the\n * supported subset).\n */\n readonly inputSchema: JsonValue;\n}\n\n/**\n * Successful projection of an MCP `CallToolResult` produced by {@link callMcpTool}.\n *\n * @remarks\n * `content` is the text concatenation of the result's `text` blocks; non-text blocks\n * (image / audio / resource) are projected to a one-line `[<type> block]` summary\n * (multimodal passthrough is out of scope at v0.1). A result with `isError: true` is mapped\n * to `Result.fail(content)` rather than returned here, so it is never silently swallowed.\n *\n * @public\n */\nexport interface IMcpToolCallResult {\n /** The projected text content of the tool result. */\n readonly content: string;\n}\n\n// ============================================================================\n// Adapter (Constraint 1)\n// ============================================================================\n\n/**\n * A tool that was discovered but could NOT be adapted into an `AiAssist.IAiClientTool`,\n * because its `inputSchema` is outside the JSON Schema subset supported by\n * `JsonSchema.fromJson`. Surfaced structurally so callers/the probe can enumerate exactly which\n * subset features a server needs (with the raw schema in hand to extend `fromJson` later).\n * @public\n */\nexport interface IMcpSkippedTool {\n /** The tool's name. */\n readonly name: string;\n /** Why the tool was skipped — the JSON-pointer reason from `JsonSchema.fromJson`, or a structural reason. */\n readonly reason: string;\n /** The raw failing input schema, verbatim, in hand for additively widening `JsonSchema.fromJson`. */\n readonly schema: JsonValue;\n}\n\n/**\n * Options for {@link adaptMcpTools}.\n * @public\n */\nexport interface IAdaptMcpToolsOptions {\n /**\n * Logger for the NOISY per-tool skip warnings. When a tool is skipped, a `warning` is emitted\n * including the tool name, the JSON-pointer reason, and the raw failing schema. When omitted,\n * skips are still surfaced structurally on {@link IAdaptMcpToolsResult.skipped}.\n */\n readonly logger?: Logging.ILogger;\n}\n\n/**\n * The result of {@link adaptMcpTools}: cleanly-adapted client tools plus the structurally-surfaced\n * set of tools that could not be adapted (graceful degradation, Constraint 1).\n * @public\n */\nexport interface IAdaptMcpToolsResult {\n /** Tools adapted into `IAiClientTool` — safe to hand to `AiAssist.executeClientToolTurn`. */\n readonly tools: ReadonlyArray<AiAssist.IAiClientTool>;\n /** Tools excluded because their `inputSchema` is outside the supported JSON Schema subset. */\n readonly skipped: ReadonlyArray<IMcpSkippedTool>;\n}\n"]}
|
|
@@ -0,0 +1,119 @@
|
|
|
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
|
+
* Tool discovery (`listMcpTools`, paginated) and invocation (`callMcpTool`, with `CallToolResult`
|
|
24
|
+
* projection), converting the throwing SDK calls into `Result<T>`.
|
|
25
|
+
* @packageDocumentation
|
|
26
|
+
*/
|
|
27
|
+
import { captureAsyncResult, fail, succeed } from '@fgv/ts-utils';
|
|
28
|
+
import { Converters } from '@fgv/ts-json-base';
|
|
29
|
+
import { McpSession } from './session';
|
|
30
|
+
/**
|
|
31
|
+
* Projects a single SDK tool descriptor into a public {@link IMcpToolDescriptor}. The
|
|
32
|
+
* `inputSchema` field is validated as a `JsonValue`; an absent/non-JSON schema becomes `null`
|
|
33
|
+
* (which {@link adaptMcpTools} then reports as un-adaptable rather than offering it to the model).
|
|
34
|
+
*/
|
|
35
|
+
function _toDescriptor(tool) {
|
|
36
|
+
return {
|
|
37
|
+
name: tool.name,
|
|
38
|
+
description: tool.description,
|
|
39
|
+
inputSchema: Converters.jsonValue.convert(tool.inputSchema).orDefault(null)
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Projects the SDK `CallToolResult` content blocks to a single string: `text` blocks are
|
|
44
|
+
* concatenated; every other block type becomes a one-line `[<type> block]` summary.
|
|
45
|
+
*/
|
|
46
|
+
function _projectContent(blocks) {
|
|
47
|
+
if (blocks === undefined || blocks.length === 0) {
|
|
48
|
+
return '';
|
|
49
|
+
}
|
|
50
|
+
return blocks
|
|
51
|
+
.map((block) => block.type === 'text' && block.text !== undefined ? block.text : `[${block.type} block]`)
|
|
52
|
+
.join('\n');
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Lists every tool a connected MCP server advertises, following the SDK's `nextCursor`
|
|
56
|
+
* pagination until the full catalog is accumulated.
|
|
57
|
+
*
|
|
58
|
+
* @param session - A session from `connectMcpSession`.
|
|
59
|
+
* @returns `Success` with the full tool catalog, or `Failure` on a foreign handle or a
|
|
60
|
+
* transport/protocol error.
|
|
61
|
+
* @public
|
|
62
|
+
*/
|
|
63
|
+
export async function listMcpTools(session) {
|
|
64
|
+
const sessionResult = McpSession.fromHandle(session);
|
|
65
|
+
if (sessionResult.isFailure()) {
|
|
66
|
+
return fail(`listMcpTools: ${sessionResult.message}`);
|
|
67
|
+
}
|
|
68
|
+
const { client } = sessionResult.value;
|
|
69
|
+
const all = [];
|
|
70
|
+
let cursor;
|
|
71
|
+
// Cursor-paginated loop: fetch each page, accumulate, advance until nextCursor is absent.
|
|
72
|
+
do {
|
|
73
|
+
const pageResult = await captureAsyncResult(() => client.listTools(cursor !== undefined ? { cursor } : undefined)).withErrorFormat((msg) => `listMcpTools: ${msg}`);
|
|
74
|
+
if (pageResult.isFailure()) {
|
|
75
|
+
return fail(pageResult.message);
|
|
76
|
+
}
|
|
77
|
+
for (const tool of pageResult.value.tools) {
|
|
78
|
+
all.push(_toDescriptor(tool));
|
|
79
|
+
}
|
|
80
|
+
cursor = pageResult.value.nextCursor;
|
|
81
|
+
} while (cursor !== undefined);
|
|
82
|
+
return succeed(all);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Calls a named tool on a connected MCP server.
|
|
86
|
+
*
|
|
87
|
+
* @remarks
|
|
88
|
+
* The SDK `CallToolResult` is projected to {@link IMcpToolCallResult} (text-block concatenation;
|
|
89
|
+
* non-text blocks summarized). A result flagged `isError: true` is mapped to `Result.fail` with
|
|
90
|
+
* the projected content — it is never swallowed, so `executeClientToolTurn` routes it back to the
|
|
91
|
+
* model as a provider-native error tool-result.
|
|
92
|
+
*
|
|
93
|
+
* @param session - A session from `connectMcpSession`.
|
|
94
|
+
* @param name - The tool name to invoke.
|
|
95
|
+
* @param args - The tool arguments (a JSON object).
|
|
96
|
+
* @returns `Success` with the projected content, or `Failure` on tool error / transport error /
|
|
97
|
+
* foreign handle.
|
|
98
|
+
* @public
|
|
99
|
+
*/
|
|
100
|
+
export async function callMcpTool(session, name, args) {
|
|
101
|
+
const sessionResult = McpSession.fromHandle(session);
|
|
102
|
+
if (sessionResult.isFailure()) {
|
|
103
|
+
return fail(`callMcpTool: ${sessionResult.message}`);
|
|
104
|
+
}
|
|
105
|
+
// The `withErrorFormat` wraps only transport/throw failures (it transforms the failure flowing
|
|
106
|
+
// out of `captureAsyncResult`); the `isError` failure created in the later `onSuccess` is
|
|
107
|
+
// downstream and stays clean, so the model-facing tool-error text is the server's verbatim
|
|
108
|
+
// content rather than a doubly-prefixed message.
|
|
109
|
+
return captureAsyncResult(() => sessionResult.value.client.callTool({ name, arguments: args }))
|
|
110
|
+
.withErrorFormat((msg) => `callMcpTool '${name}': ${msg}`)
|
|
111
|
+
.onSuccess((raw) => {
|
|
112
|
+
const content = _projectContent(raw.content);
|
|
113
|
+
if (raw.isError === true) {
|
|
114
|
+
return fail(content.length > 0 ? content : `tool '${name}' reported an error`);
|
|
115
|
+
}
|
|
116
|
+
return succeed({ content });
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
//# sourceMappingURL=operations.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"operations.js","sourceRoot":"","sources":["../../../src/packlets/mcp/operations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;;GAIG;AAEH,OAAO,EAAe,kBAAkB,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAC/E,OAAO,EAAE,UAAU,EAAmB,MAAM,mBAAmB,CAAC;AAIhE,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAEvC;;;;GAIG;AACH,SAAS,aAAa,CAAC,IAAwB;IAC7C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OAAO,KAAK,IAAI,EAAE,CAAC;YACzB,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,IAAI,qBAAqB,CAAC,CAAC;QACjF,CAAC;QACD,OAAO,OAAO,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC;IAC9B,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Tool discovery (`listMcpTools`, paginated) and invocation (`callMcpTool`, with `CallToolResult`\n * projection), converting the throwing SDK calls into `Result<T>`.\n * @packageDocumentation\n */\n\nimport { type Result, captureAsyncResult, fail, succeed } from '@fgv/ts-utils';\nimport { Converters, type JsonObject } from '@fgv/ts-json-base';\n\nimport { type IMcpSession, type IMcpToolCallResult, type IMcpToolDescriptor } from './model';\nimport { type ISdkContentBlock, type ISdkToolDescriptor } from './sdk';\nimport { McpSession } from './session';\n\n/**\n * Projects a single SDK tool descriptor into a public {@link IMcpToolDescriptor}. The\n * `inputSchema` field is validated as a `JsonValue`; an absent/non-JSON schema becomes `null`\n * (which {@link adaptMcpTools} then reports as un-adaptable rather than offering it to the model).\n */\nfunction _toDescriptor(tool: ISdkToolDescriptor): IMcpToolDescriptor {\n return {\n name: tool.name,\n description: tool.description,\n inputSchema: Converters.jsonValue.convert(tool.inputSchema).orDefault(null)\n };\n}\n\n/**\n * Projects the SDK `CallToolResult` content blocks to a single string: `text` blocks are\n * concatenated; every other block type becomes a one-line `[<type> block]` summary.\n */\nfunction _projectContent(blocks: ReadonlyArray<ISdkContentBlock> | undefined): string {\n if (blocks === undefined || blocks.length === 0) {\n return '';\n }\n return blocks\n .map((block) =>\n block.type === 'text' && block.text !== undefined ? block.text : `[${block.type} block]`\n )\n .join('\\n');\n}\n\n/**\n * Lists every tool a connected MCP server advertises, following the SDK's `nextCursor`\n * pagination until the full catalog is accumulated.\n *\n * @param session - A session from `connectMcpSession`.\n * @returns `Success` with the full tool catalog, or `Failure` on a foreign handle or a\n * transport/protocol error.\n * @public\n */\nexport async function listMcpTools(session: IMcpSession): Promise<Result<ReadonlyArray<IMcpToolDescriptor>>> {\n const sessionResult = McpSession.fromHandle(session);\n if (sessionResult.isFailure()) {\n return fail(`listMcpTools: ${sessionResult.message}`);\n }\n const { client } = sessionResult.value;\n\n const all: IMcpToolDescriptor[] = [];\n let cursor: string | undefined;\n\n // Cursor-paginated loop: fetch each page, accumulate, advance until nextCursor is absent.\n do {\n const pageResult = await captureAsyncResult(() =>\n client.listTools(cursor !== undefined ? { cursor } : undefined)\n ).withErrorFormat((msg) => `listMcpTools: ${msg}`);\n if (pageResult.isFailure()) {\n return fail(pageResult.message);\n }\n for (const tool of pageResult.value.tools) {\n all.push(_toDescriptor(tool));\n }\n cursor = pageResult.value.nextCursor;\n } while (cursor !== undefined);\n\n return succeed(all);\n}\n\n/**\n * Calls a named tool on a connected MCP server.\n *\n * @remarks\n * The SDK `CallToolResult` is projected to {@link IMcpToolCallResult} (text-block concatenation;\n * non-text blocks summarized). A result flagged `isError: true` is mapped to `Result.fail` with\n * the projected content — it is never swallowed, so `executeClientToolTurn` routes it back to the\n * model as a provider-native error tool-result.\n *\n * @param session - A session from `connectMcpSession`.\n * @param name - The tool name to invoke.\n * @param args - The tool arguments (a JSON object).\n * @returns `Success` with the projected content, or `Failure` on tool error / transport error /\n * foreign handle.\n * @public\n */\nexport async function callMcpTool(\n session: IMcpSession,\n name: string,\n args: JsonObject\n): Promise<Result<IMcpToolCallResult>> {\n const sessionResult = McpSession.fromHandle(session);\n if (sessionResult.isFailure()) {\n return fail(`callMcpTool: ${sessionResult.message}`);\n }\n // The `withErrorFormat` wraps only transport/throw failures (it transforms the failure flowing\n // out of `captureAsyncResult`); the `isError` failure created in the later `onSuccess` is\n // downstream and stays clean, so the model-facing tool-error text is the server's verbatim\n // content rather than a doubly-prefixed message.\n return captureAsyncResult(() => sessionResult.value.client.callTool({ name, arguments: args }))\n .withErrorFormat((msg) => `callMcpTool '${name}': ${msg}`)\n .onSuccess((raw): Result<IMcpToolCallResult> => {\n const content = _projectContent(raw.content);\n if (raw.isError === true) {\n return fail(content.length > 0 ? content : `tool '${name}' reported an error`);\n }\n return succeed({ content });\n });\n}\n"]}
|