@yaks/mcp-client 0.0.0-stage → 0.2.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +174 -2
- package/_dist/mod.d.ts +90 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/oauth.d.ts +46 -0
- package/_dist/oauth.d.ts.map +1 -0
- package/_dist/servers.d.ts +11 -0
- package/_dist/servers.d.ts.map +1 -0
- package/_dist/vocab.d.ts +6 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/deno.json +1 -0
- package/mod.js +371 -0
- package/mod.js.map +1 -0
- package/mod.ts +492 -0
- package/oauth.js +95 -0
- package/oauth.js.map +1 -0
- package/oauth.ts +140 -0
- package/package.json +30 -4
- package/servers.js +94 -0
- package/servers.js.map +1 -0
- package/servers.ts +93 -0
- package/vocab.js +16 -0
- package/vocab.js.map +1 -0
- package/vocab.json +81 -0
- package/vocab.ts +17 -0
package/mod.ts
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
/** MCP tools over Streamable HTTP, with no dependency on a session or a UI. */
|
|
2
|
+
// The SDK maps a subpath's types to `<subpath>.d.ts`, so a type is imported
|
|
3
|
+
// without `.js` (`sdk/types`, not `sdk/types.js`, which Deno types as any);
|
|
4
|
+
// code is still loaded from the `.js` path.
|
|
5
|
+
import type { Client } from '@modelcontextprotocol/sdk/client'
|
|
6
|
+
import type { StreamableHTTPClientTransport } from 'npm:@modelcontextprotocol/sdk@^1.29.0/client/streamableHttp'
|
|
7
|
+
import type {
|
|
8
|
+
CallToolResult,
|
|
9
|
+
Tool as RemoteTool,
|
|
10
|
+
} from 'npm:@modelcontextprotocol/sdk@^1.29.0/types'
|
|
11
|
+
import type { Tool, ToolId } from 'jsr:@yaks/graph@0.2.36'
|
|
12
|
+
import { argsOf } from '@yaks/graph/call'
|
|
13
|
+
import { errorsText, toolCheck } from '@yaks/vocab/tools'
|
|
14
|
+
import type { jsonSchemaValidator } from 'npm:@modelcontextprotocol/sdk@^1.29.0/validation'
|
|
15
|
+
|
|
16
|
+
// The MCP SDK, imported the first time a connection is used rather than when
|
|
17
|
+
// this module is: a host with no server configured never loads it, and it is
|
|
18
|
+
// most of what a harness would otherwise load at start.
|
|
19
|
+
type Sdk = {
|
|
20
|
+
Client: typeof Client
|
|
21
|
+
Transport: typeof StreamableHTTPClientTransport
|
|
22
|
+
listChanged: typeof import('npm:@modelcontextprotocol/sdk@^1.29.0/types')[
|
|
23
|
+
'ToolListChangedNotificationSchema'
|
|
24
|
+
]
|
|
25
|
+
challenge: typeof import('npm:@modelcontextprotocol/sdk@^1.29.0/client/auth')[
|
|
26
|
+
'extractWWWAuthenticateParams'
|
|
27
|
+
]
|
|
28
|
+
}
|
|
29
|
+
// `client` has its own entry in the SDK's export map. The rest load from their
|
|
30
|
+
// `.js` path, which the map types from its JS source, so each is typed by its
|
|
31
|
+
// subpath's declarations instead.
|
|
32
|
+
let typed = <M>(code: Promise<unknown>) => code as Promise<M>
|
|
33
|
+
// The runtime keeps each module once loaded, so no promise of them is kept
|
|
34
|
+
// here: one kept at module scope would be shared by every request of a Worker's
|
|
35
|
+
// isolate (@yaks/fp `Scope`).
|
|
36
|
+
let loaded = (): Promise<Sdk> =>
|
|
37
|
+
Promise.all([
|
|
38
|
+
import('@modelcontextprotocol/sdk/client'),
|
|
39
|
+
typed<typeof import('npm:@modelcontextprotocol/sdk@^1.29.0/client/streamableHttp')>(
|
|
40
|
+
import('@modelcontextprotocol/sdk/client/streamableHttp.js'),
|
|
41
|
+
),
|
|
42
|
+
typed<typeof import('npm:@modelcontextprotocol/sdk@^1.29.0/types')>(
|
|
43
|
+
import('@modelcontextprotocol/sdk/types.js'),
|
|
44
|
+
),
|
|
45
|
+
typed<typeof import('npm:@modelcontextprotocol/sdk@^1.29.0/client/auth')>(
|
|
46
|
+
import('@modelcontextprotocol/sdk/client/auth.js'),
|
|
47
|
+
),
|
|
48
|
+
]).then(([client, http, types, auth]) => ({
|
|
49
|
+
Client: client.Client,
|
|
50
|
+
Transport: http.StreamableHTTPClientTransport,
|
|
51
|
+
listChanged: types.ToolListChangedNotificationSchema,
|
|
52
|
+
challenge: auth.extractWWWAuthenticateParams,
|
|
53
|
+
}))
|
|
54
|
+
|
|
55
|
+
// The SDK's default output validator is 2020-only; remote servers also declare
|
|
56
|
+
// draft-07. Use the same dialect-aware validation as local graph tools.
|
|
57
|
+
const schemas: jsonSchemaValidator = {
|
|
58
|
+
getValidator<T>(schema: Record<string, unknown>) {
|
|
59
|
+
const check = toolCheck(schema)
|
|
60
|
+
return (input: unknown) => {
|
|
61
|
+
const errors = check(input)
|
|
62
|
+
return errors.length
|
|
63
|
+
? {
|
|
64
|
+
valid: false as const,
|
|
65
|
+
data: undefined,
|
|
66
|
+
errorMessage: errorsText(errors),
|
|
67
|
+
}
|
|
68
|
+
: { valid: true as const, data: input as T, errorMessage: undefined }
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* A reply's structured content as the text a model reads, when the reply has
|
|
75
|
+
* no text of its own. A server sends its answer twice, as text for a reader
|
|
76
|
+
* and as `structuredContent` for a parser, and a model reads one of them: the
|
|
77
|
+
* text, which the spec has carry the structured content's JSON and which is
|
|
78
|
+
* all a client that reads only text sees. A reply that wrote no text is read
|
|
79
|
+
* as its structured content.
|
|
80
|
+
*
|
|
81
|
+
* ```ts
|
|
82
|
+
* import { assertEquals } from '@std/assert'
|
|
83
|
+
* let text = { type: 'text', text: 'https://example.test/mockup/1' }
|
|
84
|
+
* let structuredContent = { saved: '<h1>mockup</h1>' }
|
|
85
|
+
* assertEquals(unsaid({ content: [text], structuredContent }), undefined)
|
|
86
|
+
* assertEquals(
|
|
87
|
+
* unsaid({ content: [], structuredContent }),
|
|
88
|
+
* '{"saved":"<h1>mockup</h1>"}',
|
|
89
|
+
* )
|
|
90
|
+
* ```
|
|
91
|
+
*/
|
|
92
|
+
export const unsaid = (
|
|
93
|
+
reply: { content?: unknown[]; structuredContent?: unknown },
|
|
94
|
+
): string | undefined =>
|
|
95
|
+
reply.structuredContent == null ||
|
|
96
|
+
(reply.content ?? []).some((b) =>
|
|
97
|
+
(b as { type?: unknown } | null)?.type == 'text'
|
|
98
|
+
)
|
|
99
|
+
? undefined
|
|
100
|
+
: JSON.stringify(reply.structuredContent)
|
|
101
|
+
|
|
102
|
+
/** A trusted server's configuration, shared across the application.
|
|
103
|
+
* Credentials are resolved separately. */
|
|
104
|
+
export type Server = {
|
|
105
|
+
name: string
|
|
106
|
+
/** Friendly display label; defaults to name. */
|
|
107
|
+
label?: string
|
|
108
|
+
/** Local namespace for public tool names; defaults to name. */
|
|
109
|
+
namespace?: string
|
|
110
|
+
url: string
|
|
111
|
+
/** The entity whose tunnel reaches the machine this server runs on. Its
|
|
112
|
+
* `url` then stands at {@link MACHINE} and only its path is meant, and only
|
|
113
|
+
* a host holding that tunnel can ask it, through the `fetch` it gives
|
|
114
|
+
* `connect`. */
|
|
115
|
+
machine?: string
|
|
116
|
+
/** Exact remote names; omission exposes all discovered tools. */
|
|
117
|
+
allow?: string[]
|
|
118
|
+
/** The header a credential is sent in, as it is kept; omission sends it
|
|
119
|
+
* as `Authorization: Bearer`. */
|
|
120
|
+
header?: string
|
|
121
|
+
/** Explicit OAuth settings; tokens stay in the application's own storage. */
|
|
122
|
+
oauth?: {
|
|
123
|
+
redirectUrl?: string
|
|
124
|
+
clientId?: string
|
|
125
|
+
clientMetadataUrl?: string
|
|
126
|
+
scope?: string
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
export type Options = {
|
|
130
|
+
token?: (server: Server) => string | null | Promise<string | null>
|
|
131
|
+
fetch?: typeof fetch
|
|
132
|
+
timeout?: number
|
|
133
|
+
}
|
|
134
|
+
export class MCPError extends Error {
|
|
135
|
+
constructor(message: string, public readonly server: string) {
|
|
136
|
+
super(message)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
export class MCPAuthorizationRequired extends MCPError {
|
|
140
|
+
constructor(
|
|
141
|
+
server: string,
|
|
142
|
+
public readonly challenge: {
|
|
143
|
+
resourceMetadataUrl?: string
|
|
144
|
+
scope?: string
|
|
145
|
+
} = {},
|
|
146
|
+
) {
|
|
147
|
+
super('MCP sign-in required; open authorization in the host', server)
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/** Where a server on a machine stands: a tunnel reaches one machine whatever
|
|
151
|
+
* host a request names, so its address is this origin and the server's path. */
|
|
152
|
+
export const MACHINE = 'http://machine'
|
|
153
|
+
|
|
154
|
+
/** Normalize only the local namespace, never the server's opaque tool name. */
|
|
155
|
+
export const namespaceOf = (name: string): string => {
|
|
156
|
+
const namespace = name.trim().replace(/[^a-zA-Z0-9_-]+/g, '_')
|
|
157
|
+
if (!namespace || !/[a-zA-Z0-9]/.test(namespace)) {
|
|
158
|
+
throw new Error('MCP server name needs a readable alphanumeric namespace')
|
|
159
|
+
}
|
|
160
|
+
return namespace
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** A provider-safe name with the exact remote name retained after the separator. */
|
|
164
|
+
export const nameOf = (server: string, name: string): string => {
|
|
165
|
+
const namespace = namespaceOf(server)
|
|
166
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
|
|
167
|
+
throw new Error(
|
|
168
|
+
'MCP remote tool name cannot be exposed unchanged: ' + name,
|
|
169
|
+
)
|
|
170
|
+
}
|
|
171
|
+
const exposed = namespace + '__' + name
|
|
172
|
+
if (exposed.length > 64) {
|
|
173
|
+
throw new Error(
|
|
174
|
+
'MCP tool name exceeds 64 characters: ' + exposed +
|
|
175
|
+
'. Use a shorter server name or ask the server for a shorter tool name.',
|
|
176
|
+
)
|
|
177
|
+
}
|
|
178
|
+
return exposed
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Refuse normalized namespace collisions rather than hiding them behind hashes. */
|
|
182
|
+
export const checkNamespaces = (servers: readonly Server[]): void => {
|
|
183
|
+
const used = new Set<string>()
|
|
184
|
+
for (const server of servers) {
|
|
185
|
+
const namespace = namespaceOf(server.namespace ?? server.name)
|
|
186
|
+
if (used.has(namespace)) {
|
|
187
|
+
throw new Error('Duplicate MCP namespace: ' + namespace)
|
|
188
|
+
}
|
|
189
|
+
used.add(namespace)
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Separators in opaque remote names can also create a cross-server collision. */
|
|
194
|
+
export const checkToolNames = (tools: readonly ToolId[]): void => {
|
|
195
|
+
const names = new Set<string>()
|
|
196
|
+
for (const tool of tools) {
|
|
197
|
+
if (names.has(tool.name!)) {
|
|
198
|
+
throw new Error('Duplicate MCP tool name: ' + tool.name)
|
|
199
|
+
}
|
|
200
|
+
names.add(tool.name!)
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export type Connection = {
|
|
205
|
+
list: () => Promise<RemoteTool[]>
|
|
206
|
+
/** What the server said to read before its tools, in its answer to
|
|
207
|
+
* `initialize` (the protocol's `instructions`), or nothing where it said
|
|
208
|
+
* none. It is the server's own text, as trusted as the server is. */
|
|
209
|
+
instructions: () => Promise<string | undefined>
|
|
210
|
+
/** What the server calls itself in its answer to `initialize` (the
|
|
211
|
+
* protocol's `serverInfo`): its `title` where it gave one, else its `name`;
|
|
212
|
+
* nothing where it gave neither. */
|
|
213
|
+
about: () => Promise<string | undefined>
|
|
214
|
+
call: (
|
|
215
|
+
name: string,
|
|
216
|
+
args: Record<string, unknown>,
|
|
217
|
+
signal?: AbortSignal,
|
|
218
|
+
) => Promise<CallToolResult>
|
|
219
|
+
refresh: () => void
|
|
220
|
+
tools: () => Promise<Tool[]>
|
|
221
|
+
close: () => Promise<void>
|
|
222
|
+
}
|
|
223
|
+
export type Clients = {
|
|
224
|
+
tools: () => Promise<Tool[]>
|
|
225
|
+
close: () => Promise<void>
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** One owned connection. connect/list are lazy; calls are never automatically replayed. */
|
|
229
|
+
export const connect = (server: Server, options: Options = {}): Connection => {
|
|
230
|
+
const url = new URL(server.url)
|
|
231
|
+
if (
|
|
232
|
+
!['http:', 'https:'].includes(url.protocol) || url.username || url.password
|
|
233
|
+
) throw new Error('MCP requires an HTTP(S) URL without embedded credentials')
|
|
234
|
+
if (server.machine && !options.fetch) {
|
|
235
|
+
throw new MCPError(
|
|
236
|
+
'An MCP server on a machine is asked through its tunnel',
|
|
237
|
+
server.name,
|
|
238
|
+
)
|
|
239
|
+
}
|
|
240
|
+
let ready: Promise<void> | undefined, closed = false, generation = 0
|
|
241
|
+
let closePromise: Promise<void> | undefined
|
|
242
|
+
let listing: Promise<RemoteTool[]> | undefined
|
|
243
|
+
let unauthorized = false
|
|
244
|
+
let challenge: { resourceMetadataUrl?: string; scope?: string } = {}
|
|
245
|
+
const fetcher: typeof fetch = async (input, init) => {
|
|
246
|
+
const headers = new Headers(init?.headers)
|
|
247
|
+
const token = await options.token?.(server)
|
|
248
|
+
if (token) {
|
|
249
|
+
const target = new URL(
|
|
250
|
+
input instanceof Request ? input.url : String(input),
|
|
251
|
+
)
|
|
252
|
+
if (target.origin !== url.origin) {
|
|
253
|
+
throw new MCPError(
|
|
254
|
+
'Refusing cross-origin credential forwarding',
|
|
255
|
+
server.name,
|
|
256
|
+
)
|
|
257
|
+
}
|
|
258
|
+
if (
|
|
259
|
+
url.protocol !== 'https:' &&
|
|
260
|
+
!['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
|
|
261
|
+
) throw new MCPError('Credentials require HTTPS', server.name)
|
|
262
|
+
if (server.header) headers.set(server.header, token)
|
|
263
|
+
else headers.set('authorization', `Bearer ${token}`)
|
|
264
|
+
}
|
|
265
|
+
const response = await (options.fetch ?? fetch)(input, {
|
|
266
|
+
...init,
|
|
267
|
+
headers,
|
|
268
|
+
redirect: 'manual',
|
|
269
|
+
signal: init?.signal
|
|
270
|
+
? AbortSignal.any([
|
|
271
|
+
init.signal,
|
|
272
|
+
AbortSignal.timeout(options.timeout ?? 60000),
|
|
273
|
+
])
|
|
274
|
+
: AbortSignal.timeout(options.timeout ?? 60000),
|
|
275
|
+
})
|
|
276
|
+
// A machine's tunnel is its host's already: a 401 there asks for no sign-in.
|
|
277
|
+
if (response.status === 401 && !server.machine) {
|
|
278
|
+
unauthorized = true
|
|
279
|
+
const found = (await loaded()).challenge(response)
|
|
280
|
+
challenge = {
|
|
281
|
+
resourceMetadataUrl: found.resourceMetadataUrl?.href,
|
|
282
|
+
scope: found.scope,
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return response
|
|
286
|
+
}
|
|
287
|
+
// The client and its transport, made the first time the connection is used.
|
|
288
|
+
let opened: Promise<[Client, StreamableHTTPClientTransport]> | undefined
|
|
289
|
+
const open = () =>
|
|
290
|
+
opened ??= loaded().then((m) => {
|
|
291
|
+
const sdk = new m.Client(
|
|
292
|
+
{ name: 'yaks-mcp-client', version: '0.1.0' },
|
|
293
|
+
{ jsonSchemaValidator: schemas, capabilities: {} },
|
|
294
|
+
)
|
|
295
|
+
sdk.setNotificationHandler(m.listChanged, () => {
|
|
296
|
+
generation++
|
|
297
|
+
listing = undefined
|
|
298
|
+
})
|
|
299
|
+
return [sdk, new m.Transport(url, { fetch: fetcher })]
|
|
300
|
+
})
|
|
301
|
+
const ensure = async (): Promise<Client> => {
|
|
302
|
+
if (closed) throw new MCPError('MCP connection is closed', server.name)
|
|
303
|
+
const [sdk, transport] = await open()
|
|
304
|
+
await (ready ??= sdk.connect(transport).catch(async () => {
|
|
305
|
+
await sdk.close().catch(() => {})
|
|
306
|
+
if (unauthorized) {
|
|
307
|
+
throw new MCPAuthorizationRequired(server.name, challenge)
|
|
308
|
+
}
|
|
309
|
+
throw new MCPError(
|
|
310
|
+
server.machine
|
|
311
|
+
? 'MCP connection failed; the machine may be off, or not open this path to its tunnel'
|
|
312
|
+
: 'MCP connection failed; check server URL and sign-in',
|
|
313
|
+
server.name,
|
|
314
|
+
)
|
|
315
|
+
}))
|
|
316
|
+
return sdk
|
|
317
|
+
}
|
|
318
|
+
const list = async (): Promise<RemoteTool[]> => {
|
|
319
|
+
const sdk = await ensure()
|
|
320
|
+
if (!listing) {
|
|
321
|
+
unauthorized = false
|
|
322
|
+
const observed = generation
|
|
323
|
+
const pending = (async () => {
|
|
324
|
+
const all: RemoteTool[] = [], cursors = new Set<string>()
|
|
325
|
+
let cursor: string | undefined
|
|
326
|
+
do {
|
|
327
|
+
const page = await sdk.listTools(cursor ? { cursor } : {}, {
|
|
328
|
+
timeout: options.timeout ?? 60000,
|
|
329
|
+
})
|
|
330
|
+
all.push(...page.tools)
|
|
331
|
+
cursor = page.nextCursor
|
|
332
|
+
if (cursor && cursors.has(cursor)) {
|
|
333
|
+
throw new MCPError('Repeated tools/list cursor', server.name)
|
|
334
|
+
}
|
|
335
|
+
if (cursor) cursors.add(cursor)
|
|
336
|
+
if (all.length > 1000) {
|
|
337
|
+
throw new MCPError(
|
|
338
|
+
'MCP discovery exceeded 1000 tools',
|
|
339
|
+
server.name,
|
|
340
|
+
)
|
|
341
|
+
}
|
|
342
|
+
} while (cursor)
|
|
343
|
+
const seen = new Set<string>()
|
|
344
|
+
for (const t of all) {
|
|
345
|
+
if (seen.has(t.name)) {
|
|
346
|
+
throw new MCPError('Duplicate remote tool name', server.name)
|
|
347
|
+
}
|
|
348
|
+
seen.add(t.name)
|
|
349
|
+
}
|
|
350
|
+
return all.filter((t) => !server.allow || server.allow.includes(t.name))
|
|
351
|
+
})().catch((e) => {
|
|
352
|
+
if (unauthorized) {
|
|
353
|
+
throw new MCPAuthorizationRequired(server.name, challenge)
|
|
354
|
+
}
|
|
355
|
+
throw e
|
|
356
|
+
})
|
|
357
|
+
listing = pending
|
|
358
|
+
pending.catch(() => {
|
|
359
|
+
if (listing === pending) listing = undefined
|
|
360
|
+
})
|
|
361
|
+
const answer = await pending
|
|
362
|
+
if (observed !== generation) listing = undefined
|
|
363
|
+
return answer
|
|
364
|
+
}
|
|
365
|
+
return listing
|
|
366
|
+
}
|
|
367
|
+
const call = async (
|
|
368
|
+
name: string,
|
|
369
|
+
args: Record<string, unknown>,
|
|
370
|
+
signal?: AbortSignal,
|
|
371
|
+
): Promise<CallToolResult> => {
|
|
372
|
+
const sdk = await ensure()
|
|
373
|
+
if (server.allow && !server.allow.includes(name)) {
|
|
374
|
+
throw new MCPError('Tool not allowed', server.name)
|
|
375
|
+
}
|
|
376
|
+
unauthorized = false
|
|
377
|
+
try {
|
|
378
|
+
return await sdk.callTool({ name, arguments: args }, undefined, {
|
|
379
|
+
signal,
|
|
380
|
+
timeout: options.timeout ?? 60000,
|
|
381
|
+
}) as CallToolResult
|
|
382
|
+
} catch {
|
|
383
|
+
if (unauthorized) {
|
|
384
|
+
throw new MCPAuthorizationRequired(server.name, challenge)
|
|
385
|
+
}
|
|
386
|
+
// Do not expose endpoint response bodies or credentials, or retry uncertain writes.
|
|
387
|
+
throw new MCPError(
|
|
388
|
+
'MCP call failed; remote outcome may be unknown. No retry was performed.',
|
|
389
|
+
server.name,
|
|
390
|
+
)
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return {
|
|
394
|
+
list,
|
|
395
|
+
instructions: async () => (await ensure()).getInstructions() || undefined,
|
|
396
|
+
about: async () => {
|
|
397
|
+
const info = (await ensure()).getServerVersion()
|
|
398
|
+
return info?.title?.trim() || info?.name?.trim() || undefined
|
|
399
|
+
},
|
|
400
|
+
call,
|
|
401
|
+
refresh: () => {
|
|
402
|
+
generation++
|
|
403
|
+
listing = undefined
|
|
404
|
+
},
|
|
405
|
+
tools: async (): Promise<Tool[]> => {
|
|
406
|
+
const listed = await list()
|
|
407
|
+
if (new Set(listed.map((t) => t.name)).size !== listed.length) {
|
|
408
|
+
throw new Error('Duplicate remote MCP tool name')
|
|
409
|
+
}
|
|
410
|
+
return Promise.all(listed.map(async (t) => ({
|
|
411
|
+
name: await nameOf(server.namespace ?? server.name, t.name),
|
|
412
|
+
...(t.title ?? t.annotations?.title
|
|
413
|
+
? { title: t.title ?? t.annotations?.title }
|
|
414
|
+
: {}),
|
|
415
|
+
step: {
|
|
416
|
+
doing: `Using ${server.label ?? server.name}…`,
|
|
417
|
+
done: `Used ${server.label ?? server.name}`,
|
|
418
|
+
},
|
|
419
|
+
description: `[${server.label ?? server.name}] ${
|
|
420
|
+
t.description ?? t.name
|
|
421
|
+
}`,
|
|
422
|
+
inputSchema: t.inputSchema,
|
|
423
|
+
readOnly: t.annotations?.readOnlyHint,
|
|
424
|
+
destructive: t.annotations?.destructiveHint,
|
|
425
|
+
idempotent: t.annotations?.idempotentHint,
|
|
426
|
+
openWorld: t.annotations?.openWorldHint,
|
|
427
|
+
meta: { server: server.name, remoteName: t.name },
|
|
428
|
+
// A tool on another server replies in the MCP result format, and this
|
|
429
|
+
// graph stores text: the reply's text blocks, or its structured
|
|
430
|
+
// content where it wrote none ({@link unsaid}), written as one entity
|
|
431
|
+
// recording which call produced it. A caller that needs the reply
|
|
432
|
+
// whole — artifacts, resources, the error flag — calls the
|
|
433
|
+
// connection's own `call` instead.
|
|
434
|
+
run: async (asked) => {
|
|
435
|
+
let reply = await call(t.name, argsOf(asked))
|
|
436
|
+
let blocks = (reply.content ?? []) as Record<string, unknown>[]
|
|
437
|
+
let said = blocks
|
|
438
|
+
.filter((block) => block.type == 'text')
|
|
439
|
+
.map((block) => String(block.text ?? ''))
|
|
440
|
+
let structured = unsaid(reply)
|
|
441
|
+
if (structured) said.push(structured)
|
|
442
|
+
return [{
|
|
443
|
+
entity: { eid: '$said' },
|
|
444
|
+
content: { body: said.join('\n') },
|
|
445
|
+
output: { source: asked.entity.eid },
|
|
446
|
+
...(reply.isError ? { refusal: { code: 'mcp_tool' } } : {}),
|
|
447
|
+
}]
|
|
448
|
+
},
|
|
449
|
+
})))
|
|
450
|
+
},
|
|
451
|
+
close: (): Promise<void> =>
|
|
452
|
+
closePromise ??= (async () => {
|
|
453
|
+
closed = true
|
|
454
|
+
// Never used, nothing was opened; an opening under way ends first.
|
|
455
|
+
if (!opened) return
|
|
456
|
+
const [sdk, transport] = await opened
|
|
457
|
+
// A transport failure must not strand the local event stream.
|
|
458
|
+
try {
|
|
459
|
+
if (transport.sessionId) await transport.terminateSession()
|
|
460
|
+
} finally {
|
|
461
|
+
await sdk.close()
|
|
462
|
+
}
|
|
463
|
+
})(),
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** Several configured connections at once, usable from a CLI, from graph
|
|
468
|
+
* tools, or from anywhere else. */
|
|
469
|
+
export const clients = (
|
|
470
|
+
servers: readonly Server[],
|
|
471
|
+
options: Options = {},
|
|
472
|
+
): Clients => {
|
|
473
|
+
checkNamespaces(servers)
|
|
474
|
+
const names = new Set<string>()
|
|
475
|
+
for (const s of servers) {
|
|
476
|
+
if (!s.name || names.has(s.name)) {
|
|
477
|
+
throw new Error('MCP server names must be nonempty and unique')
|
|
478
|
+
}
|
|
479
|
+
names.add(s.name)
|
|
480
|
+
}
|
|
481
|
+
const all = servers.map((s) => connect(s, options))
|
|
482
|
+
return {
|
|
483
|
+
tools: async (): Promise<Tool[]> => {
|
|
484
|
+
const tools = (await Promise.all(all.map((c) => c.tools()))).flat()
|
|
485
|
+
checkToolNames(tools)
|
|
486
|
+
return tools
|
|
487
|
+
},
|
|
488
|
+
close: async () => {
|
|
489
|
+
await Promise.all(all.map((c) => c.close()))
|
|
490
|
+
},
|
|
491
|
+
}
|
|
492
|
+
}
|
package/oauth.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/** Where an MCP server signs in, found the way the MCP spec says: its
|
|
2
|
+
* protected-resource metadata (RFC 9728) names the authorization server, whose
|
|
3
|
+
* own metadata (RFC 8414) names the endpoints, and a public client is named
|
|
4
|
+
* there by the host's own metadata document where the server takes one (a
|
|
5
|
+
* Client ID Metadata Document, its URL the client's id), else registers there
|
|
6
|
+
* (RFC 7591), when the host has none. What comes back is data, an
|
|
7
|
+
* integration as @yaks/connections takes it; the sign-in, the tokens and their
|
|
8
|
+
* refresh are @yaks/oauth's over that data. No UI, storage or session. */ // The SDK's discovery and registration, imported when a sign-in is looked for
|
|
9
|
+
// rather than when this module is (./mod.ts says why).
|
|
10
|
+
let auth = ()=>import("@modelcontextprotocol/sdk/client/auth.js");
|
|
11
|
+
/** What the host's public client says of itself, returning to `redirect`:
|
|
12
|
+
* what it registers with (RFC 7591), and its metadata document, served at
|
|
13
|
+
* `id`, the URL that is its id where a server takes one.
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* import { assertEquals } from '@std/assert'
|
|
17
|
+
* let doc = client('https://h.test/oauth/client.json', 'https://h.test/cb')
|
|
18
|
+
* assertEquals([doc.client_id, doc.redirect_uris], [
|
|
19
|
+
* 'https://h.test/oauth/client.json', ['https://h.test/cb'],
|
|
20
|
+
* ])
|
|
21
|
+
* ```
|
|
22
|
+
*/ export const client = (id, redirect)=>({
|
|
23
|
+
...id ? {
|
|
24
|
+
client_id: safe(id)
|
|
25
|
+
} : {},
|
|
26
|
+
client_name: 'yaks.app MCP client',
|
|
27
|
+
redirect_uris: [
|
|
28
|
+
safe(redirect)
|
|
29
|
+
],
|
|
30
|
+
grant_types: [
|
|
31
|
+
'authorization_code',
|
|
32
|
+
'refresh_token'
|
|
33
|
+
],
|
|
34
|
+
response_types: [
|
|
35
|
+
'code'
|
|
36
|
+
],
|
|
37
|
+
token_endpoint_auth_method: 'none'
|
|
38
|
+
});
|
|
39
|
+
export class AuthorizationError extends Error {
|
|
40
|
+
}
|
|
41
|
+
// HTTPS, or HTTP on this machine: what a code, a token or a registration may
|
|
42
|
+
// travel over.
|
|
43
|
+
const safe = (url)=>{
|
|
44
|
+
const u = new URL(url);
|
|
45
|
+
if (u.username || u.password || u.protocol !== 'https:' && !(u.protocol === 'http:' && [
|
|
46
|
+
'127.0.0.1',
|
|
47
|
+
'localhost',
|
|
48
|
+
'[::1]'
|
|
49
|
+
].includes(u.hostname))) throw new AuthorizationError('OAuth requires HTTPS or a loopback URL');
|
|
50
|
+
return u.href;
|
|
51
|
+
};
|
|
52
|
+
/** Find where the server at `url` signs in. The integration is named for the
|
|
53
|
+
* server, sends its tokens to the server's host alone, and asks for the grant
|
|
54
|
+
* to be for the server (RFC 8707). `document` is the URL the host serves its
|
|
55
|
+
* client's metadata document at ({@link client}), where it serves one. */ export const discover = async (url, challenge = {}, fetch = globalThis.fetch, document)=>{
|
|
56
|
+
const fetchFn = (input, init)=>fetch(safe(input instanceof Request ? input.url : String(input)), {
|
|
57
|
+
...init,
|
|
58
|
+
redirect: 'manual',
|
|
59
|
+
signal: AbortSignal.timeout(30000)
|
|
60
|
+
});
|
|
61
|
+
const { discoverOAuthServerInfo, registerClient } = await auth();
|
|
62
|
+
const info = await discoverOAuthServerInfo(safe(url), {
|
|
63
|
+
resourceMetadataUrl: challenge.resourceMetadataUrl ? new URL(challenge.resourceMetadataUrl) : undefined,
|
|
64
|
+
fetchFn
|
|
65
|
+
});
|
|
66
|
+
const meta = info.authorizationServerMetadata;
|
|
67
|
+
if (!meta) throw new AuthorizationError('The server names no sign-in');
|
|
68
|
+
const scope = challenge.scope ?? info.resourceMetadata?.scopes_supported?.join(' ');
|
|
69
|
+
return {
|
|
70
|
+
integration: {
|
|
71
|
+
name: url,
|
|
72
|
+
authorize: safe(meta.authorization_endpoint),
|
|
73
|
+
token: safe(meta.token_endpoint),
|
|
74
|
+
...typeof meta.userinfo_endpoint == 'string' ? {
|
|
75
|
+
userinfo: safe(meta.userinfo_endpoint)
|
|
76
|
+
} : {},
|
|
77
|
+
...scope ? {
|
|
78
|
+
scopes: scope.split(' ')
|
|
79
|
+
} : {},
|
|
80
|
+
resource: url,
|
|
81
|
+
...'authorization_response_iss_parameter_supported' in meta && meta.authorization_response_iss_parameter_supported ? {
|
|
82
|
+
issuer: meta.issuer
|
|
83
|
+
} : {},
|
|
84
|
+
hosts: [
|
|
85
|
+
new URL(url).hostname
|
|
86
|
+
]
|
|
87
|
+
},
|
|
88
|
+
register: async (redirect)=>document && meta.client_id_metadata_document_supported ? safe(document) : (await registerClient(info.authorizationServerUrl, {
|
|
89
|
+
metadata: meta,
|
|
90
|
+
clientMetadata: client(undefined, redirect),
|
|
91
|
+
fetchFn
|
|
92
|
+
})).client_id
|
|
93
|
+
};
|
|
94
|
+
};
|
|
95
|
+
//# sourceMappingURL=oauth.js.map
|
package/oauth.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth.js","sources":["./oauth.ts"],"names":[],"mappings":"AAAA;;;;;;;wEAOwE,GAExE,8EAA8E;AAC9E,uDAAuD;AACvD,IAAI,OAAO,IACT,MAAM,CAAC;AAqCT;;;;;;;;;;;CAWC,GACD,OAAO,MAAM,SAAS,CACpB,IACA,WACmB,CAAC;IACpB,GAAG,KAAK;MAAE,WAAW,KAAK;IAAI,IAAI,CAAC,CAAC;IACpC,aAAa;IACb,eAAe;MAAC,KAAK;KAAU;IAC/B,aAAa;MAAC;MAAsB;KAAgB;IACpD,gBAAgB;MAAC;KAAO;IACxB,4BAA4B;EAC9B,CAAC,EAAC;AAEF,OAAO,MAAM,2BAA2B;AAAO;AAE/C,6EAA6E;AAC7E,eAAe;AACf,MAAM,OAAO,CAAC;EACZ,MAAM,IAAI,IAAI,IAAI;EAClB,IACE,EAAE,QAAQ,IAAI,EAAE,QAAQ,IAAK,EAAE,QAAQ,KAAK,YAC1C,CAAC,CAAC,EAAE,QAAQ,KAAK,WACf;IAAC;IAAa;IAAa;GAAQ,CAAC,QAAQ,CAAC,EAAE,QAAQ,CAAC,GAC5D,MAAM,IAAI,mBAAmB;EAC/B,OAAO,EAAE,IAAI;AACf;AAEA;;;wEAGwE,GACxE,OAAO,MAAM,WAAW,OACtB,KACA,YAAoC,CAAC,CAAC,EACtC,QAAiC,WAAW,KAAK,EACjD;EAEA,MAAM,UAAmC,CAAC,OAAO,OAC/C,MAAM,KAAK,iBAAiB,UAAU,MAAM,GAAG,GAAG,OAAO,SAAS;MAChE,GAAG,IAAI;MACP,UAAU;MACV,QAAQ,YAAY,OAAO,CAAC;IAC9B;EACF,MAAM,EAAE,uBAAuB,EAAE,cAAc,EAAE,GAAG,MAAM;EAC1D,MAAM,OAAO,MAAM,wBAAwB,KAAK,MAAM;IACpD,qBAAqB,UAAU,mBAAmB,GAC9C,IAAI,IAAI,UAAU,mBAAmB,IACrC;IACJ;EACF;EACA,MAAM,OAAO,KAAK,2BAA2B;EAC7C,IAAI,CAAC,MAAM,MAAM,IAAI,mBAAmB;EACxC,MAAM,QAAQ,UAAU,KAAK,IAC3B,KAAK,gBAAgB,EAAE,kBAAkB,KAAK;EAChD,OAAO;IACL,aAAa;MACX,MAAM;MACN,WAAW,KAAK,KAAK,sBAAsB;MAC3C,OAAO,KAAK,KAAK,cAAc;MAC/B,GAAG,OAAO,KAAK,iBAAiB,IAAI,WAChC;QAAE,UAAU,KAAK,KAAK,iBAAiB;MAAE,IACzC,CAAC,CAAC;MACN,GAAG,QAAQ;QAAE,QAAQ,MAAM,KAAK,CAAC;MAAK,IAAI,CAAC,CAAC;MAC5C,UAAU;MACV,GAAG,oDAAoD,QACnD,KAAK,8CAA8C,GACnD;QAAE,QAAQ,KAAK,MAAM;MAAC,IACtB,CAAC,CAAC;MACN,OAAO;QAAC,IAAI,IAAI,KAAK,QAAQ;OAAC;IAChC;IACA,UAAU,OAAO,WACf,YAAY,KAAK,qCAAqC,GAClD,KAAK,YACL,CAAC,MAAM,eAAe,KAAK,sBAAsB,EAAE;QACnD,UAAU;QACV,gBAAgB,OAAO,WAAW;QAClC;MACF,EAAE,EAAE,SAAS;EACnB;AACF,EAAC"}
|