@reinsjs/tools-mcp 0.3.10 → 0.4.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # @reinsjs/tools-mcp
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 38b2689: Pick a credential per `tools/call` on one MCP server: `mcpTools({ transport, route: { keyOf(call, ctx), transportFor(key) } })`.
8
+
9
+ - `transport` stays the catalog connection: `tools/list` runs on it once per run start and `optional` applies to it alone. `route` is not part of the tool table or config hash, so changing routing rules is not configuration drift.
10
+ - Each call asks `keyOf` for a key and runs on a per-key connection from a pool owned by the socket (lazy, reused across runs, rebuilt once after a drop). Each key's recipe carries its own `auth`, so a 401 refreshes that identity alone.
11
+ - `keyOf` returning anything but a non-empty string, or throwing, means the call is not sent; it never falls back to the catalog connection. A thrown message reaches the model verbatim.
12
+ - If the run is aborted before the call is sent (in `keyOf`, `transportFor` or a new key's handshake), the model gets `ROUTE_NOT_SENT_TEXT` ("Not executed: …") rather than the loop's "outcome unknown" text.
13
+ - New `McpToolsSocket.evict(key)`: removes a key from the pool at once and closes its connection after the calls in flight on it finish. `close()` now also closes every pooled connection, evicted ones still draining included. Hand-written test doubles of `McpToolsSocket` need an `evict` method.
14
+ - The pool is shared by every session that reaches the socket: `keyOf` is the only authorization point. See the README section "Several credentials on one server".
15
+
16
+ ## 0.3.11
17
+
18
+ ### Patch Changes
19
+
20
+ - Updated dependencies [884c840]
21
+ - @reinsjs/core@0.14.0
22
+
3
23
  ## 0.3.10
4
24
 
5
25
  ### Patch Changes
package/README.md CHANGED
@@ -86,7 +86,8 @@ no retry policy inside a call: a failed call is reported to the model as an erro
86
86
  run start throws before anything is written to the log (fail-closed). Pass `optional: true` to instead start the
87
87
  run without that server's tools and warn once; the model then sees them listed as removed.
88
88
 
89
- Call `close()` when you are done with a socket (process shutdown, or the host replaced the configuration).
89
+ Call `close()` when you are done with a socket (process shutdown, or the host replaced the configuration). With
90
+ `route`, `evict(key)` retires one credential's connection; see [Several credentials on one server](#several-credentials-on-one-server).
90
91
 
91
92
  Hosts that build the agent per request should **cache sockets by configuration**, not rebuild them every time:
92
93
  rebuilding forces a fresh MCP handshake per request. `examples/mcp/agent.ts` shows a small cache keyed by the
@@ -131,6 +132,101 @@ which a server-side agent cannot do. Obtain and store the tokens in your web app
131
132
  refreshes them. Full OAuth flows are still not wrapped — call the SDK's `refreshAuthorization` (or your own code)
132
133
  from inside `token` / `onUnauthorized`.
133
134
 
135
+ One user with several credentials on the same server (several identities, same catalog) is a different shape:
136
+ see the next section.
137
+
138
+ ## Several credentials on one server
139
+
140
+ One user may hold several identities on the same server: several TikTok for Business authorizations, each a
141
+ separate OAuth token, each seeing the same tool catalog but a different set of ad accounts. The model should only
142
+ decide *what to do to which account*; which identity carries the call is an authorization rule, and it belongs to
143
+ the host. Pass `route`:
144
+
145
+ ```ts
146
+ import { httpTransport, type McpRoute, type McpTransport, mcpTools } from "@reinsjs/tools-mcp"
147
+
148
+ /** Calls that touch no account. Only these run on the catalog identity. */
149
+ const NO_ACCOUNT = new Set(["tool_list", "tool_get"])
150
+
151
+ /** Every argument that names an account. TikTok's gateway tool nests them under `params`. */
152
+ const accountsOf = (name: string, args: unknown): string[] => {
153
+ const top = (typeof args === "object" && args !== null ? args : {}) as Record<string, unknown>
154
+ const inner = name === "tool_execute" ? top.params : top
155
+ const fields = (typeof inner === "object" && inner !== null ? inner : {}) as Record<string, unknown>
156
+ return ["advertiser_id", "bc_id"]
157
+ .map((field) => fields[field])
158
+ .filter((id) => typeof id === "string" || typeof id === "number")
159
+ .map(String)
160
+ }
161
+
162
+ interface Identities {
163
+ /** The identity used for tools/list and for calls that touch no account */
164
+ catalog: string
165
+ /** Which identity may act on this account for this person; undefined when none may */
166
+ forAccount(account: string, principalId: string | undefined): Promise<string | undefined>
167
+ transport(identity: string): McpTransport
168
+ }
169
+
170
+ const routeByAccount = (ids: Identities): McpRoute => ({
171
+ async keyOf({ name, args }, ctx) {
172
+ if (NO_ACCOUNT.has(name)) return ids.catalog
173
+ const accounts = accountsOf(name, args)
174
+ if (accounts.length === 0) throw new Error(`Cannot tell which account ${name} acts on`)
175
+ const chosen = new Set<string>()
176
+ for (const account of accounts) {
177
+ const identity = await ids.forAccount(account, ctx.principal?.id)
178
+ if (identity === undefined)
179
+ throw new Error(`No connected TikTok identity can access account ${account}`)
180
+ chosen.add(identity)
181
+ }
182
+ if (chosen.size > 1)
183
+ throw new Error(`Accounts ${accounts.join(", ")} need different identities; use one per call`)
184
+ return [...chosen][0] as string
185
+ },
186
+ transportFor: (identity) => ids.transport(identity),
187
+ })
188
+
189
+ // ids.transport(identity) = httpTransport({ url, auth: { token: () => db.accessToken(identity), onUnauthorized: … } })
190
+ const tiktok = mcpTools({ transport: ids.transport(ids.catalog), route: routeByAccount(ids) })
191
+ ```
192
+
193
+ What happens:
194
+
195
+ - `transport` is still the **catalog connection**: `tools/list` runs on it once at run start, and `optional`
196
+ applies to it alone. The tool table, and therefore the config hash, does not depend on `route`, so changing the
197
+ routing rules never counts as configuration drift. The identities are assumed to see the same catalog; when one
198
+ lacks a tool, the server's error reaches the model as an error result.
199
+ - Every `tools/call` first asks `keyOf`. The returned key picks a connection from a pool owned by the socket;
200
+ a new key calls `transportFor(key)` once and the connection then follows the usual lifecycle (lazy, reused
201
+ across runs, rebuilt once after a drop). Each key's recipe carries its own `auth`, so a 401 refreshes that
202
+ identity alone.
203
+ - `keyOf` returning anything but a non-empty string, or throwing, means the call is **not sent** — never sent on
204
+ the catalog connection instead. A thrown message reaches the model verbatim, so write it for the model.
205
+ - If the run is stopped while the call is still being routed (inside `keyOf`, `transportFor` or a new key's
206
+ handshake), the model is told the call was not executed (`ROUTE_NOT_SENT_TEXT`), not that its outcome is unknown.
207
+ - Call `evict(key)` when a credential is revoked, expires or gets a new recipe. The key leaves the pool at once;
208
+ its connection closes after the calls in flight on it finish, so a write that already reached the server is not
209
+ cut off and reported as a failure. `close()` does not wait: it closes everything, evicted connections included.
210
+
211
+ Things you are responsible for:
212
+
213
+ - **`keyOf` is the only authorization point.** The pool is keyed by credential only, and a cached socket is shared
214
+ by every session and user that reaches it. Check in `keyOf` that `ctx.principal` may use that identity. Fail
215
+ closed the way the recipe does: only an explicit list of account-free tools may use the catalog identity, a call
216
+ whose account you cannot find is refused rather than sent on some default identity, and every argument that
217
+ names an account must resolve to the same identity. Extend `accountsOf` with every account-naming argument your
218
+ server has.
219
+ - **`transportFor` must depend on the key alone.** It runs once per key, not once per call, so anything
220
+ request-specific it captured would leak to later callers.
221
+ - **Approval happens before routing.** The approver does not see which identity will carry the call unless you
222
+ compute it in the approval rule's `summary` with the same function.
223
+ - **The catalog credential cannot be evicted on its own.** If it is revoked, `close()` the socket and build a new
224
+ one (the pool goes with it and is rebuilt on demand).
225
+ - Each pooled connection keeps a standing SSE stream open once initialized (MCP SDK behaviour). The pool has no
226
+ size limit; it holds as many connections as there are keys you route to until you evict them.
227
+
228
+ `packages/tools-mcp/src/multi-credential.recipe.test.ts` is the executable version of this recipe.
229
+
134
230
  ## Gateway-style servers
135
231
 
136
232
  Some servers put hundreds of operations behind **one** dispatching tool. TikTok for Business is the current
@@ -264,6 +360,7 @@ rejection. Script: `spikes/mcp-removed-tool-history`.
264
360
  | `callTimeoutMs` | 60 000 | Per `tools/call` timeout; expiry becomes an error result |
265
361
  | `optional` | `false` | On `tools/list` failure at run start: throw (default) or contribute no tools and warn once |
266
362
  | `override(tool, info)` | — | Per-tool rewrite; return `false` to drop the tool |
363
+ | `route` | — | `{ keyOf(call, ctx), transportFor(key) }`: pick a credential per `tools/call`; `transport` then serves `tools/list` only |
267
364
  | `clientInfo` | `{ name: "reins", version }` | Sent in the MCP handshake |
268
365
  | `warn` | `console.warn` | Where degradations are reported |
269
366
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as McpAuth, a as McpTransport, b as McpToolsOptions, c as McpToolsSocket, d as McpToolAnnotations, e as McpToolInfo } from './types-F_1Kfslp.js';
2
- export { f as McpToolsError } from './types-F_1Kfslp.js';
1
+ import { M as McpAuth, a as McpTransport, b as McpToolsOptions, c as McpToolsSocket, d as McpToolAnnotations, e as McpToolInfo } from './types-JwDpisKk.js';
2
+ export { f as McpRoute, g as McpRoutedCall, h as McpToolsError } from './types-JwDpisKk.js';
3
3
  import { Tool, ContentPart } from '@reinsjs/core';
4
4
 
5
5
  interface HttpTransportOptions {
@@ -24,6 +24,13 @@ declare const REINS_MCP_CLIENT_INFO: {
24
24
  name: string;
25
25
  version: string;
26
26
  };
27
+ /**
28
+ * 路由阶段(选凭据、建连握手,还没发出 `tools/call`)run 被中止时给模型的结果。不能让 execute 抛:MCP 工具缺省不可重放,
29
+ * 循环已先写 `tool_started`,中止状态下抛错会被写成"结果未知",而调用实际没发出——告诉模型的要与事实一致。
30
+ * 前缀与 core 的"没执行"文案同为 `Not executed:`,宿主按前缀判断时口径一致;不复用 `stopTextsOf`:它对非 RunStop 的中止
31
+ * (丢租约等)也说"被用户停止"
32
+ */
33
+ declare const ROUTE_NOT_SENT_TEXT = "Not executed: the run was interrupted before this call was sent to the MCP server.";
27
34
  declare function mcpTools(options: McpToolsOptions): McpToolsSocket;
28
35
 
29
36
  /**
@@ -66,4 +73,4 @@ interface McpCallResult {
66
73
  */
67
74
  declare function toContentParts(result: McpCallResult): ContentPart[];
68
75
 
69
- export { DEFAULT_CALL_TIMEOUT_MS, type HttpTransportOptions, MODEL_TOOL_NAME_RE, McpAuth, McpToolAnnotations, McpToolInfo, McpToolsOptions, McpToolsSocket, McpTransport, REINS_MCP_CLIENT_INFO, httpTransport, mcpTools, modelToolName, riskOf, toContentParts, toToolInfo };
76
+ export { DEFAULT_CALL_TIMEOUT_MS, type HttpTransportOptions, MODEL_TOOL_NAME_RE, McpAuth, McpToolAnnotations, McpToolInfo, McpToolsOptions, McpToolsSocket, McpTransport, REINS_MCP_CLIENT_INFO, ROUTE_NOT_SENT_TEXT, httpTransport, mcpTools, modelToolName, riskOf, toContentParts, toToolInfo };
package/dist/index.js CHANGED
@@ -185,6 +185,13 @@ var McpConnection = class {
185
185
  this.connecting = void 0;
186
186
  }
187
187
  }
188
+ /**
189
+ * 确保连接已建好(握手完成)。`route` 把握手放进"发出前"那一段:握手期间 run 被中止时请求根本没发出,
190
+ * 调用方据此如实告诉模型"没发出",而不是让 SDK 在发请求处抛错、被循环写成"结果未知"
191
+ */
192
+ async ready() {
193
+ await this.ensure();
194
+ }
188
195
  /** `tools/list`(SDK 会自动翻完全部分页)。绕过 SDK 的列表缓存:每次 run 起步要的就是服务器此刻的表 */
189
196
  async listTools(signal) {
190
197
  const client = await this.ensure();
@@ -230,9 +237,80 @@ function messageOf(err) {
230
237
  return err instanceof Error ? err.message : String(err);
231
238
  }
232
239
 
240
+ // src/route-pool.ts
241
+ var RoutePool = class {
242
+ constructor(route, options) {
243
+ this.route = route;
244
+ this.options = options;
245
+ }
246
+ route;
247
+ options;
248
+ entries = /* @__PURE__ */ new Map();
249
+ /** 已被 evict 移出、还在等在途归零的项。`closeAll` 收摊时一并关掉,否则它们会拖到 evict 自己关为止 */
250
+ draining = /* @__PURE__ */ new Set();
251
+ /**
252
+ * 取该键的池项并占一个在途名额(同步,见文件头);调用方必须在 `finally` 里 `release`。
253
+ * 没有就按 `transportFor(key)` 新建;它抛错或返回不合规时不入池,原样抛出(下次再路由到该键会重新调)
254
+ */
255
+ acquire(key) {
256
+ let entry = this.entries.get(key);
257
+ if (!entry) {
258
+ const transport = this.route.transportFor(key);
259
+ if (!isTransport(transport))
260
+ throw new TypeError(`route.transportFor must return an McpTransport, got ${kindOf(transport)}`);
261
+ entry = { conn: new McpConnection(transport, this.options), inflight: 0 };
262
+ this.entries.set(key, entry);
263
+ }
264
+ entry.inflight++;
265
+ return entry;
266
+ }
267
+ release(entry) {
268
+ entry.inflight--;
269
+ if (entry.inflight === 0) entry.onDrained?.();
270
+ }
271
+ /** 立即移出,等在途调用结束再关。同一键连调两次时第二次立即返回(项已不在池里) */
272
+ async evict(key) {
273
+ const entry = this.entries.get(key);
274
+ if (!entry) return;
275
+ this.entries.delete(key);
276
+ this.draining.add(entry);
277
+ try {
278
+ if (entry.inflight > 0)
279
+ await new Promise((resolve) => {
280
+ entry.onDrained = resolve;
281
+ });
282
+ await entry.conn.close();
283
+ } finally {
284
+ this.draining.delete(entry);
285
+ }
286
+ }
287
+ /**
288
+ * 收摊:关掉池里全部连接(含正在等在途归零的被 evict 项)、清空池,不等在途调用(与 `McpToolsSocket.close` 同义)。
289
+ * 被 evict 项之后在 evict 里再关一次是无操作(`McpConnection.close` 幂等)。全部尝试后有失败抛第一个
290
+ */
291
+ async closeAll() {
292
+ const conns = [...this.entries.values(), ...this.draining].map((e) => e.conn);
293
+ this.entries.clear();
294
+ const results = await Promise.allSettled(conns.map((c) => c.close()));
295
+ const failed = results.find((r) => r.status === "rejected");
296
+ if (failed) throw failed.reason;
297
+ }
298
+ };
299
+ function isTransport(value) {
300
+ if (typeof value !== "object" || value === null) return false;
301
+ const t = value;
302
+ return typeof t.create === "function" && typeof t.label === "string";
303
+ }
304
+ function kindOf(value) {
305
+ if (value === null) return "null";
306
+ if (value === "") return "an empty string";
307
+ return typeof value;
308
+ }
309
+
233
310
  // src/mcp-tools.ts
234
311
  var DEFAULT_CALL_TIMEOUT_MS = 6e4;
235
312
  var REINS_MCP_CLIENT_INFO = { name: "reins", version: REINS_VERSION };
313
+ var ROUTE_NOT_SENT_TEXT = "Not executed: the run was interrupted before this call was sent to the MCP server.";
236
314
  function mcpTools(options) {
237
315
  const { transport } = options;
238
316
  const warn = options.warn ?? ((m) => console.warn(m));
@@ -240,7 +318,16 @@ function mcpTools(options) {
240
318
  const timeoutMs = options.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS;
241
319
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
242
320
  throw new RangeError("callTimeoutMs must be a positive number");
243
- const conn = new McpConnection(transport, { clientInfo: options.clientInfo ?? REINS_MCP_CLIENT_INFO });
321
+ const route = options.route;
322
+ if (route) {
323
+ if (typeof route.keyOf !== "function")
324
+ throw new TypeError(`route.keyOf must be a function, got ${kindOf(route.keyOf)}`);
325
+ if (typeof route.transportFor !== "function")
326
+ throw new TypeError(`route.transportFor must be a function, got ${kindOf(route.transportFor)}`);
327
+ }
328
+ const connectionOptions = { clientInfo: options.clientInfo ?? REINS_MCP_CLIENT_INFO };
329
+ const conn = new McpConnection(transport, connectionOptions);
330
+ const pool = route ? new RoutePool(route, connectionOptions) : void 0;
244
331
  const warned = /* @__PURE__ */ new Set();
245
332
  const warnOnce = (key, message) => {
246
333
  if (warned.has(key)) return;
@@ -263,11 +350,32 @@ function mcpTools(options) {
263
350
  // 明说破坏性的工具缺省要人点头;循环内置兜底会在没有 Socket 做主时直接转审批
264
351
  ...risk === "high" ? { needsApproval: true } : {},
265
352
  async execute(args, ctx) {
266
- const result = await conn.callTool(info.name, args, {
267
- timeoutMs,
268
- ...ctx.signal ? { signal: ctx.signal } : {}
269
- });
270
- return { content: toContentParts(result), isError: result.isError === true };
353
+ const callOptions = { timeoutMs, ...ctx.signal ? { signal: ctx.signal } : {} };
354
+ if (!route || !pool) {
355
+ const result = await conn.callTool(info.name, args, callOptions);
356
+ return { content: toContentParts(result), isError: result.isError === true };
357
+ }
358
+ let entry;
359
+ try {
360
+ try {
361
+ const key = await route.keyOf({ name: info.name, args }, ctx);
362
+ if (typeof key !== "string" || key === "")
363
+ throw new Error(
364
+ `MCP route must return a non-empty credential key for tool ${info.name}, got ${kindOf(key)}; the call was not sent`
365
+ );
366
+ if (ctx.signal?.aborted) return notSent();
367
+ entry = pool.acquire(key);
368
+ await entry.conn.ready();
369
+ if (ctx.signal?.aborted) return notSent();
370
+ } catch (err) {
371
+ if (ctx.signal?.aborted) return notSent();
372
+ throw err;
373
+ }
374
+ const result = await entry.conn.callTool(info.name, args, callOptions);
375
+ return { content: toContentParts(result), isError: result.isError === true };
376
+ } finally {
377
+ if (entry) pool.release(entry);
378
+ }
271
379
  }
272
380
  });
273
381
  };
@@ -295,9 +403,19 @@ function mcpTools(options) {
295
403
  }
296
404
  return tools;
297
405
  },
298
- close: () => conn.close()
406
+ close: async () => {
407
+ const results = await Promise.allSettled([conn.close(), pool?.closeAll()]);
408
+ const failed = results.find((r) => r.status === "rejected");
409
+ if (failed) throw failed.reason;
410
+ },
411
+ evict: async (key) => {
412
+ await pool?.evict(key);
413
+ }
299
414
  };
300
415
  }
416
+ function notSent() {
417
+ return { content: [{ type: "text", text: ROUTE_NOT_SENT_TEXT }], isError: true };
418
+ }
301
419
  function messageOf2(err) {
302
420
  return err instanceof Error ? err.message : String(err);
303
421
  }
@@ -306,6 +424,7 @@ export {
306
424
  MODEL_TOOL_NAME_RE,
307
425
  McpToolsError,
308
426
  REINS_MCP_CLIENT_INFO,
427
+ ROUTE_NOT_SENT_TEXT,
309
428
  httpTransport,
310
429
  mcpTools,
311
430
  modelToolName,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/http.ts","../src/mcp-tools.ts","../src/connection.ts","../src/translate.ts","../src/types.ts"],"sourcesContent":["/**\n * Streamable HTTP 传输配方(主入口,纯 Web 标准:只用 fetch / URL / Headers)。\n *\n * 固定令牌用 `headers: { Authorization: \"Bearer …\" }` 就够。会过期的令牌(OAuth)必须用 `auth`:\n * headers 在构造时就定死了,而连接是懒建、跨 run 复用、断了按同一配方重建的——令牌一过期,重建也是拿旧的。\n * `auth.token()` 每个请求前现取,401 时 `onUnauthorized()` 刷新后自动重试一次(都由 MCP SDK 的传输层做)。\n */\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/client\"\nimport type { McpAuth, McpTransport } from \"./types.js\"\n\nexport interface HttpTransportOptions {\n url: string | URL\n /** 每个请求附带的头(固定令牌等)。会过期的令牌用 `auth`,别写死在这里 */\n headers?: Record<string, string>\n /**\n * 每个请求的 bearer 凭证来源:`token()` 请求前现取、401 走 `onUnauthorized()` 刷新后自动重试一次。\n * 与 `headers.Authorization` 互斥(两者都给在构造期即拒绝:静默让一个盖掉另一个,排查时看不出来)\n */\n auth?: McpAuth\n /** 自定义 fetch(代理、测试里直连内存服务器) */\n fetch?: typeof fetch\n /** 其余 RequestInit 字段(headers 之外) */\n requestInit?: Omit<RequestInit, \"headers\">\n}\n\n/** headers 里的 Authorization(大小写不敏感:HTTP 头名不区分大小写,宿主写 authorization 也算) */\nfunction hasAuthorizationHeader(headers: Record<string, string> | undefined): boolean {\n if (!headers) return false\n return Object.keys(headers).some((k) => k.toLowerCase() === \"authorization\")\n}\n\nexport function httpTransport(options: HttpTransportOptions): McpTransport {\n if (options.auth && hasAuthorizationHeader(options.headers)) {\n throw new Error(\n \"httpTransport: auth and an Authorization header cannot be used together; keep the token in auth.token() so it is fetched fresh for every request\",\n )\n }\n const url = options.url instanceof URL ? options.url : new URL(options.url)\n // 标签只留主机与路径:查询串里常见 token,不进日志\n const label = `${url.origin}${url.pathname}`\n // 包一层而不是直接把 McpAuth 交给 SDK:我们的签名收 MaybePromise,宿主同步返回令牌也行\n const auth = options.auth\n const authProvider = auth\n ? {\n token: async () => await auth.token(),\n ...(auth.onUnauthorized ? { onUnauthorized: async () => void (await auth.onUnauthorized?.()) } : {}),\n }\n : undefined\n return {\n kind: \"http\",\n label,\n create: () =>\n new StreamableHTTPClientTransport(url, {\n requestInit: { ...options.requestInit, ...(options.headers ? { headers: options.headers } : {}) },\n ...(options.fetch ? { fetch: options.fetch } : {}),\n ...(authProvider ? { authProvider } : {}),\n }),\n }\n}\n","/**\n * `mcpTools(options): Socket` —— 把一台 MCP 服务器接成 reins 的一个 Socket(技术方案 §10,任务 P1)。\n *\n * 形状刻意最小:只用 Socket 的静态贡献 `tools`(异步函数),一个钩子都不挂。\n * - run 起步 `tools/list` 一次 → 每个 MCP 工具翻成 reins `Tool`,整个 run 工具表不变(§9.1 约束 3 / PRD\"不做动态注册\");\n * 服务器中途发 `listChanged` 只影响下一次 run —— 下一次起步再 list 一遍自然拿到新表,循环还会把增删告诉模型(tools_bound)。\n * - `execute` = `tools/call`;结果 content 翻成 ContentPart、`isError` 直通;抛错(未知工具、断连、超时)由循环记成\n * `tool_result(isError)`,循环不崩。\n * - annotations → `risk` 与 `needsApproval` 缺省(readOnly → low;destructive → high + 要审批;其余 medium)。\n * spill / approval / budget 在 afterTool / beforeTool 上自动生效,MCP 服务器不需要知道 reins(P3)。\n */\nimport { defineTool, REINS_VERSION, type Tool } from \"@reinsjs/core\"\nimport { McpConnection } from \"./connection.js\"\nimport { modelToolName, riskOf, toContentParts } from \"./translate.js\"\nimport type { McpToolInfo, McpToolsOptions, McpToolsSocket } from \"./types.js\"\n\nexport const DEFAULT_CALL_TIMEOUT_MS = 60_000\n/** MCP initialize 握手里报给服务器的客户端身份;版本跟随 core,不另维护一份 */\nexport const REINS_MCP_CLIENT_INFO = { name: \"reins\", version: REINS_VERSION }\n\nexport function mcpTools(options: McpToolsOptions): McpToolsSocket {\n const { transport } = options\n const warn = options.warn ?? ((m: string) => console.warn(m))\n const prefix = options.prefix ?? \"\"\n const timeoutMs = options.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)\n throw new RangeError(\"callTimeoutMs must be a positive number\")\n const conn = new McpConnection(transport, { clientInfo: options.clientInfo ?? REINS_MCP_CLIENT_INFO })\n const warned = new Set<string>()\n const warnOnce = (key: string, message: string) => {\n if (warned.has(key)) return\n warned.add(key)\n warn(message)\n }\n\n /** 一个 MCP 工具 → reins Tool。名字给模型看的可能被改写,调用时用原名 */\n const toTool = (info: McpToolInfo): Tool => {\n const name = modelToolName(info.name, prefix)\n if (name !== `${prefix}${info.name}`)\n warnOnce(\n `name:${info.name}`,\n `MCP tool name ${info.name} does not meet the model-facing requirements; the name shown to the model is rewritten to ${name}`,\n )\n const risk = riskOf(info.annotations)\n return defineTool<unknown>({\n name,\n description: info.description ?? info.title ?? info.name,\n inputSchema: info.inputSchema,\n risk,\n // 明说破坏性的工具缺省要人点头;循环内置兜底会在没有 Socket 做主时直接转审批\n ...(risk === \"high\" ? { needsApproval: true } : {}),\n async execute(args, ctx) {\n const result = await conn.callTool(info.name, args, {\n timeoutMs,\n ...(ctx.signal ? { signal: ctx.signal } : {}),\n })\n return { content: toContentParts(result), isError: result.isError === true }\n },\n })\n }\n\n return {\n name: `mcp:${transport.label}`,\n transport,\n tools: async () => {\n let infos: McpToolInfo[]\n try {\n infos = await conn.listTools()\n } catch (err) {\n if (!options.optional) throw err\n warnOnce(\n \"list\",\n `MCP server ${transport.label} is unavailable, so this run carries none of its tools: ${messageOf(err)}`,\n )\n return []\n }\n const tools: Tool[] = []\n for (const info of infos) {\n const tool = toTool(info)\n const overridden = options.override?.(tool, info)\n if (overridden === false) continue\n tools.push(overridden ?? tool)\n }\n return tools\n },\n close: () => conn.close(),\n }\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * 一条 MCP 连接的生命周期:懒建、跨 run 复用、断了下次需要时按配方重建一次、宿主可关。\n *\n * 为什么不在这里做重连策略(退避、次数):库里的连接是给\"多次 run 复用\"的,一次 `tools/call` 失败就让模型\n * 看到 isError 自己决定要不要再试(宪法一);跨 run 的\"重建一次\"只是把\"上次断了\"这个状态清掉,\n * 不是重试。真要保活、要退避的宿主自己包一层 transport。\n */\nimport { Client, type Transport } from \"@modelcontextprotocol/client\"\nimport type { McpCallResult } from \"./translate.js\"\nimport { toToolInfo } from \"./translate.js\"\nimport { type McpToolInfo, McpToolsError, type McpTransport } from \"./types.js\"\n\nexport interface McpConnectionOptions {\n clientInfo: { name: string; version: string }\n}\n\nexport class McpConnection {\n private client: Client | undefined\n private connecting: Promise<Client> | undefined\n\n constructor(\n readonly transport: McpTransport,\n private readonly options: McpConnectionOptions,\n ) {}\n\n /** 当前是否持有一条活连接(测试与排错用) */\n get connected(): boolean {\n return this.client !== undefined\n }\n\n /** 拿到已连接的 Client:没有就建;正在建就等同一次;上次断了(onclose 已清掉)就重建 */\n private async ensure(): Promise<Client> {\n if (this.client) return this.client\n if (this.connecting) return this.connecting\n this.connecting = (async () => {\n const client = new Client(this.options.clientInfo)\n try {\n await client.connect(this.transport.create() as Transport)\n } catch (err) {\n throw new McpToolsError(\n `Failed to connect to MCP server (${this.transport.label}): ${messageOf(err)}`,\n this.transport.label,\n { cause: err },\n )\n }\n // 传输断开(服务器退出、网络断):清掉引用,下一次 ensure 重建。不在这里自动重连\n client.onclose = () => {\n if (this.client === client) this.client = undefined\n }\n this.client = client\n return client\n })()\n try {\n return await this.connecting\n } finally {\n this.connecting = undefined\n }\n }\n\n /** `tools/list`(SDK 会自动翻完全部分页)。绕过 SDK 的列表缓存:每次 run 起步要的就是服务器此刻的表 */\n async listTools(signal?: AbortSignal): Promise<McpToolInfo[]> {\n const client = await this.ensure()\n let result: { tools: unknown[] }\n try {\n result = await client.listTools({}, { cacheMode: \"bypass\", ...(signal ? { signal } : {}) })\n } catch (err) {\n throw new McpToolsError(\n `MCP tools/list failed (${this.transport.label}): ${messageOf(err)}`,\n this.transport.label,\n { cause: err },\n )\n }\n return result.tools.map(toToolInfo)\n }\n\n /** `tools/call`。抛错(未知工具、断连、超时)交给调用方翻成 isError 结果 */\n async callTool(\n name: string,\n args: unknown,\n opts: { signal?: AbortSignal; timeoutMs: number },\n ): Promise<McpCallResult> {\n const client = await this.ensure()\n const result = await client.callTool(\n { name, arguments: (args ?? {}) as Record<string, unknown> },\n { timeout: opts.timeoutMs, ...(opts.signal ? { signal: opts.signal } : {}) },\n )\n return result as McpCallResult\n }\n\n /**\n * 关掉当前连接(宿主热轮换 Socket、进程收尾)。\n * 正在建连时调用:等这次建连有结果再关——否则 `ensure()` 完成后会把新 Client 挂回 `this.client`,\n * 连接泄漏、`onclose` 回调悬挂(2026-09-10 审查修)。建连失败本来就没有连接,吞掉那个错误。\n */\n async close(): Promise<void> {\n if (this.connecting) {\n try {\n await this.connecting\n } catch {\n // 建连失败:没有连接可关\n }\n }\n const client = this.client\n this.client = undefined\n if (client) await client.close()\n }\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * MCP ⇄ reins 的纯函数翻译:工具声明 → `Tool` 的静态部分,`tools/call` 结果 → `ContentPart[]`。\n * 不碰网络、不碰事件,单测直接喂 JSON。\n *\n * 有损的地方都在这里明说(P7):reins 的 ContentPart 只有文本与图片,MCP 的 audio / 二进制 resource\n * 翻成一行说明文字告诉模型\"有这么个东西但看不到\",不静默丢。\n */\nimport type { ContentPart, Tool } from \"@reinsjs/core\"\nimport type { McpToolAnnotations, McpToolInfo } from \"./types.js\"\n\n/** Anthropic / OpenAI 对工具名的共同要求;MCP 没有这个限制,不合规的名字要改写,否则请求 400 */\nexport const MODEL_TOOL_NAME_RE = /^[A-Za-z0-9_-]{1,64}$/\n\n/** 给模型看的名字:加前缀、把不合规字符换成 `_`、截到 64。返回值与原名不同则调用方应告警一次 */\nexport function modelToolName(mcpName: string, prefix = \"\"): string {\n const raw = `${prefix}${mcpName}`\n if (MODEL_TOOL_NAME_RE.test(raw)) return raw\n const cleaned = raw.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 64)\n return cleaned.length > 0 ? cleaned : \"_\"\n}\n\n/**\n * 注解 → 风险档。spec 说注解只是提示、不可信服务器的注解不能当权限依据,所以这里只定**缺省值**:\n * 明说只读 → low;明说破坏性 → high(并缺省要审批);其余(含完全没注解)→ medium,交给 approval 模块的策略。\n * 注意 spec 里 destructiveHint 缺省为 true,我们刻意不把\"没写\"当\"破坏性\"——否则每个 MCP 工具都要审批,\n * 宿主要那么严可以用 `override` 自己定。\n */\nexport function riskOf(annotations: McpToolAnnotations | undefined): NonNullable<Tool[\"risk\"]> {\n if (annotations?.destructiveHint === true) return \"high\"\n if (annotations?.readOnlyHint === true) return \"low\"\n return \"medium\"\n}\n\n/** `tools/list` 里的一项 → 纯数据 McpToolInfo;形状不对就抛(服务器声明不合法,宁可起步失败) */\nexport function toToolInfo(raw: unknown): McpToolInfo {\n if (typeof raw !== \"object\" || raw === null) throw new TypeError(\"MCP tool declaration is not an object\")\n const t = raw as Record<string, unknown>\n if (typeof t.name !== \"string\" || t.name.length === 0)\n throw new TypeError(\"MCP tool declaration has no name\")\n if (typeof t.inputSchema !== \"object\" || t.inputSchema === null)\n throw new TypeError(`MCP tool ${t.name} has no inputSchema`)\n const info: McpToolInfo = { name: t.name, inputSchema: t.inputSchema as Record<string, unknown> }\n if (typeof t.title === \"string\") info.title = t.title\n if (typeof t.description === \"string\") info.description = t.description\n if (typeof t.outputSchema === \"object\" && t.outputSchema !== null)\n info.outputSchema = t.outputSchema as Record<string, unknown>\n if (typeof t.annotations === \"object\" && t.annotations !== null)\n info.annotations = t.annotations as McpToolAnnotations\n return info\n}\n\n/** base64 文本对应的字节数(去掉填充) */\nfunction base64Bytes(b64: string): number {\n const padding = b64.endsWith(\"==\") ? 2 : b64.endsWith(\"=\") ? 1 : 0\n return Math.max(0, Math.floor((b64.length * 3) / 4) - padding)\n}\n\n/** `tools/call` 结果的形状(只取我们用到的字段;SDK 类型不出本包) */\nexport interface McpCallResult {\n content?: unknown\n structuredContent?: unknown\n isError?: unknown\n}\n\n/**\n * MCP 内容块 → reins 内容片段。\n * - text → 文本;image → 图片(mime + base64)\n * - audio → 音频片段(2026-11-05 起;MCP 没有时长,估算走字节折算);缺 data 或 mime 不是 audio/* 时一行说明\n * - resource_link → 一行 \"Resource link: uri (name) [mime]\"\n * - resource(内嵌):文本资源 → 带 uri 头的文本;image/* / video/* / audio/* 二进制 → 对应片段(MCP 没有 video 块,\n * 视频只会从这里来);其他二进制 → 一行说明\n * 模型收不收视频 / 音频由降级层按能力位处置(不收落占位),这里只管如实翻译\n * - 不认识的块 → JSON 文本(不静默丢)\n * - content 为空而有 structuredContent → 其 JSON;都没有 → 空文本(模型总得有个结果块)\n */\nexport function toContentParts(result: McpCallResult): ContentPart[] {\n const blocks = Array.isArray(result.content) ? result.content : []\n const parts: ContentPart[] = []\n for (const raw of blocks) {\n const b = (typeof raw === \"object\" && raw !== null ? raw : {}) as Record<string, unknown>\n switch (b.type) {\n case \"text\":\n parts.push({ type: \"text\", text: typeof b.text === \"string\" ? b.text : \"\" })\n break\n case \"image\":\n if (typeof b.data === \"string\" && typeof b.mimeType === \"string\")\n parts.push({ type: \"image\", mime: b.mimeType, data: b.data })\n else parts.push({ type: \"text\", text: \"[image block without data/mimeType]\" })\n break\n case \"audio\": {\n if (typeof b.data === \"string\" && typeof b.mimeType === \"string\" && b.mimeType.startsWith(\"audio/\")) {\n parts.push({ type: \"audio\", mime: b.mimeType, data: b.data })\n break\n }\n const bytes = typeof b.data === \"string\" ? base64Bytes(b.data) : 0\n parts.push({\n type: \"text\",\n text: `[audio ${String(b.mimeType ?? \"unknown type\")}, ${bytes} bytes; audio cannot be shown to the model]`,\n })\n break\n }\n case \"resource_link\": {\n const name = typeof b.name === \"string\" ? ` (${b.name})` : \"\"\n const mime = typeof b.mimeType === \"string\" ? ` [${b.mimeType}]` : \"\"\n const desc = typeof b.description === \"string\" ? ` — ${b.description}` : \"\"\n parts.push({ type: \"text\", text: `Resource link: ${String(b.uri)}${name}${mime}${desc}` })\n break\n }\n case \"resource\": {\n const r = (typeof b.resource === \"object\" && b.resource !== null ? b.resource : {}) as Record<\n string,\n unknown\n >\n const uri = String(r.uri ?? \"\")\n const mime = typeof r.mimeType === \"string\" ? r.mimeType : undefined\n if (typeof r.text === \"string\") {\n parts.push({ type: \"text\", text: `[resource ${uri}${mime ? ` (${mime})` : \"\"}]\\n${r.text}` })\n } else if (typeof r.blob === \"string\" && mime?.startsWith(\"image/\")) {\n parts.push({ type: \"image\", mime, data: r.blob })\n } else if (typeof r.blob === \"string\" && mime?.startsWith(\"video/\")) {\n parts.push({ type: \"video\", mime, data: r.blob })\n } else if (typeof r.blob === \"string\" && mime?.startsWith(\"audio/\")) {\n parts.push({ type: \"audio\", mime, data: r.blob })\n } else {\n const bytes = typeof r.blob === \"string\" ? base64Bytes(r.blob) : 0\n parts.push({\n type: \"text\",\n text: `[binary resource ${uri}${mime ? ` (${mime})` : \"\"}, ${bytes} bytes; not shown to the model]`,\n })\n }\n break\n }\n default:\n parts.push({ type: \"text\", text: JSON.stringify(raw) ?? String(raw) })\n }\n }\n if (parts.length === 0) {\n if (result.structuredContent !== undefined && result.structuredContent !== null)\n parts.push({ type: \"text\", text: JSON.stringify(result.structuredContent) ?? \"\" })\n else parts.push({ type: \"text\", text: \"\" })\n }\n return parts\n}\n","/**\n * @reinsjs/tools-mcp 的公开类型。MCP SDK 的类型一律不出本包(同降级层对 pi-ai 的约束):\n * 对外只有 reins 自己的 `Tool` / `Socket`,加上这里几个纯数据形状。\n */\nimport type { MaybePromise, Socket, Tool } from \"@reinsjs/core\"\n\n/**\n * 每个请求的 bearer 凭证来源(HTTP 传输)。刻意只有两个方法、且不引用 MCP SDK 的类型:\n * 形状与 SDK 的 `AuthProvider` 结构兼容,宿主不必 import SDK。\n *\n * **不收 SDK 的 `OAuthClientProvider`**:那套的核心是\"开浏览器让人点授权\",在服务端 agent 里跑不通——\n * 令牌该由宿主的 Web 应用先拿好、存起来,循环里只负责取用与刷新。完整 OAuth 流程仍不封装(0.1 立场不变),\n * 宿主要用可以在 `token` / `onUnauthorized` 里自己调 SDK 的 `refreshAuthorization` 等函数。\n */\nexport interface McpAuth {\n /** 每个请求发出前调用。返回 undefined 表示这次不带 Authorization 头 */\n token(): MaybePromise<string | undefined>\n /**\n * 服务器回 401 时调用,之后传输层**自动重试该请求一次**;重试再 401(或没给这个方法)就抛错。\n * 实现里该做的是刷新令牌——下一次 `token()` 要能返回可用的那个\n */\n onUnauthorized?(): MaybePromise<void>\n}\n\n/** MCP 工具注解(spec 里全部是\"提示\",只用来给 risk / needsApproval 定缺省值,不当权限判定) */\nexport interface McpToolAnnotations {\n title?: string\n readOnlyHint?: boolean\n destructiveHint?: boolean\n idempotentHint?: boolean\n openWorldHint?: boolean\n}\n\n/** `tools/list` 返回的一个工具,原样搬过来的纯数据;`override` 钩子拿它做逐工具改写的依据 */\nexport interface McpToolInfo {\n name: string\n title?: string\n description?: string\n inputSchema: Record<string, unknown>\n outputSchema?: Record<string, unknown>\n annotations?: McpToolAnnotations\n}\n\n/**\n * 一条 MCP 传输的\"配方\":怎么建出底层连接。主入口只有 `httpTransport`(Streamable HTTP,纯 Web 标准),\n * `@reinsjs/tools-mcp/node` 才有 `stdioTransport`(起子进程)。连接本身由 `mcpTools()` 懒建、跨 run 复用,\n * 断了在下一次需要时按这个配方重建一次 —— 所以配方必须可重复调用。\n */\nexport interface McpTransport {\n readonly kind: \"http\" | \"stdio\" | \"custom\"\n /** 给 Socket.name、告警与报错用的可读标签(不含密钥) */\n readonly label: string\n /**\n * 建一条新的底层传输。返回值是 MCP SDK 的 Transport,对外按 unknown 处理(SDK 类型不出本包);\n * 自定义传输(如测试用的内存传输)也从这里进\n */\n create(): unknown\n}\n\nexport interface McpToolsOptions {\n transport: McpTransport\n /**\n * 给模型看的工具名前缀(如 `\"gh_\"`),多台服务器同名工具靠它区分;缺省无。\n * 调用时按原名发给服务器。宿主工具与 MCP 工具同名时以宿主为准(core 静态贡献的既有规则)\n */\n prefix?: string\n /** 单次 `tools/call` 超时毫秒,缺省 60_000;到点抛错 → 模型看到 isError 结果,循环不崩 */\n callTimeoutMs?: number\n /**\n * run 起步 `tools/list` 失败时怎么办。缺省 false:抛错,run 在写任何日志之前失败(fail-closed,宿主一定知道)。\n * true:本次 run 不贡献工具、告警一次,模型会从工具变化说明里看到这些工具被移除了\n */\n optional?: boolean\n /**\n * 逐工具改写:调整 needsApproval / risk / resultPolicy / description 等;返回 `false` 即不把这个工具给模型。\n * 入参 `tool` 是按缺省规则翻好的 reins Tool,`info` 是服务器原样的声明\n */\n override?(tool: Tool, info: McpToolInfo): Tool | false | undefined\n /** MCP 握手时的客户端自述,缺省 `{ name: \"reins\", version: <本包版本> }` */\n clientInfo?: { name: string; version: string }\n /** 告警出口(optional 降级、工具名被改写),缺省 console.warn */\n warn?: (message: string) => void\n}\n\nexport interface McpToolsSocket extends Socket {\n readonly transport: McpTransport\n /** 关掉底层连接。进程退出、或宿主按请求重建配置时换掉旧的之前调;关掉后再跑 run 会按配方重建 */\n close(): Promise<void>\n}\n\n/** 本包抛出的错误:连接建不起来、`tools/list` 失败、服务器声明不合法 */\nexport class McpToolsError extends Error {\n constructor(\n message: string,\n readonly transport: string,\n options?: { cause?: unknown },\n ) {\n super(message, options)\n this.name = \"McpToolsError\"\n }\n}\n"],"mappings":";AAOA,SAAS,qCAAqC;AAmB9C,SAAS,uBAAuB,SAAsD;AACpF,MAAI,CAAC,QAAS,QAAO;AACrB,SAAO,OAAO,KAAK,OAAO,EAAE,KAAK,CAAC,MAAM,EAAE,YAAY,MAAM,eAAe;AAC7E;AAEO,SAAS,cAAc,SAA6C;AACzE,MAAI,QAAQ,QAAQ,uBAAuB,QAAQ,OAAO,GAAG;AAC3D,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,QAAM,MAAM,QAAQ,eAAe,MAAM,QAAQ,MAAM,IAAI,IAAI,QAAQ,GAAG;AAE1E,QAAM,QAAQ,GAAG,IAAI,MAAM,GAAG,IAAI,QAAQ;AAE1C,QAAM,OAAO,QAAQ;AACrB,QAAM,eAAe,OACjB;AAAA,IACE,OAAO,YAAY,MAAM,KAAK,MAAM;AAAA,IACpC,GAAI,KAAK,iBAAiB,EAAE,gBAAgB,YAAY,KAAM,MAAM,KAAK,iBAAiB,EAAG,IAAI,CAAC;AAAA,EACpG,IACA;AACJ,SAAO;AAAA,IACL,MAAM;AAAA,IACN;AAAA,IACA,QAAQ,MACN,IAAI,8BAA8B,KAAK;AAAA,MACrC,aAAa,EAAE,GAAG,QAAQ,aAAa,GAAI,QAAQ,UAAU,EAAE,SAAS,QAAQ,QAAQ,IAAI,CAAC,EAAG;AAAA,MAChG,GAAI,QAAQ,QAAQ,EAAE,OAAO,QAAQ,MAAM,IAAI,CAAC;A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YAAY,KAAK;AAAA,MAC7E;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL,MAAM,OAAO,UAAU,KAAK;AAAA,IAC5B;AAAA,IACA,OAAO,YAAY;AACjB,UAAI;AACJ,UAAI;AACF,gBAAQ,MAAM,KAAK,UAAU;AAAA,MAC/B,SAAS,KAAK;AACZ,YAAI,CAAC,QAAQ,SAAU,OAAM;AAC7B;AAAA,UACE;AAAA,UACA,cAAc,UAAU,KAAK,2DAA2DA,WAAU,GAAG,CAAC;AAAA,QACxG;AACA,eAAO,CAAC;AAAA,MACV;AACA,YAAM,QAAgB,CAAC;AACvB,iBAAW,QAAQ,OAAO;AACxB,cAAM,OAAO,OAAO,IAAI;AACxB,cAAM,aAAa,QAAQ,WAAW,MAAM,IAAI;AAChD,YAAI,eAAe,MAAO;AAC1B,cAAM,KAAK,cAAc,IAAI;AAAA,MAC/B;AACA,aAAO;AAAA,IACT;AAAA,IACA,OAAO,MAAM,KAAK,MAAM;AAAA,EAC1B;AACF;AAEA,SAASA,WAAU,KAAsB;AACvC,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;","names":["messageOf"]}
1
+ {"version":3,"sources":["../src/http.ts","../src/mcp-tools.ts","../src/connection.ts","../src/translate.ts","../src/types.ts","../src/route-pool.ts"],"sourcesContent":["/**\n * Streamable HTTP 传输配方(主入口,纯 Web 标准:只用 fetch / URL / Headers)。\n *\n * 固定令牌用 `headers: { Authorization: \"Bearer …\" }` 就够。会过期的令牌(OAuth)必须用 `auth`:\n * headers 在构造时就定死了,而连接是懒建、跨 run 复用、断了按同一配方重建的——令牌一过期,重建也是拿旧的。\n * `auth.token()` 每个请求前现取,401 时 `onUnauthorized()` 刷新后自动重试一次(都由 MCP SDK 的传输层做)。\n */\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/client\"\nimport type { McpAuth, McpTransport } from \"./types.js\"\n\nexport interface HttpTransportOptions {\n url: string | URL\n /** 每个请求附带的头(固定令牌等)。会过期的令牌用 `auth`,别写死在这里 */\n headers?: Record<string, string>\n /**\n * 每个请求的 bearer 凭证来源:`token()` 请求前现取、401 走 `onUnauthorized()` 刷新后自动重试一次。\n * 与 `headers.Authorization` 互斥(两者都给在构造期即拒绝:静默让一个盖掉另一个,排查时看不出来)\n */\n auth?: McpAuth\n /** 自定义 fetch(代理、测试里直连内存服务器) */\n fetch?: typeof fetch\n /** 其余 RequestInit 字段(headers 之外) */\n requestInit?: Omit<RequestInit, \"headers\">\n}\n\n/** headers 里的 Authorization(大小写不敏感:HTTP 头名不区分大小写,宿主写 authorization 也算) */\nfunction hasAuthorizationHeader(headers: Record<string, string> | undefined): boolean {\n if (!headers) return false\n return Object.keys(headers).some((k) => k.toLowerCase() === \"authorization\")\n}\n\nexport function httpTransport(options: HttpTransportOptions): McpTransport {\n if (options.auth && hasAuthorizationHeader(options.headers)) {\n throw new Error(\n \"httpTransport: auth and an Authorization header cannot be used together; keep the token in auth.token() so it is fetched fresh for every request\",\n )\n }\n const url = options.url instanceof URL ? options.url : new URL(options.url)\n // 标签只留主机与路径:查询串里常见 token,不进日志\n const label = `${url.origin}${url.pathname}`\n // 包一层而不是直接把 McpAuth 交给 SDK:我们的签名收 MaybePromise,宿主同步返回令牌也行\n const auth = options.auth\n const authProvider = auth\n ? {\n token: async () => await auth.token(),\n ...(auth.onUnauthorized ? { onUnauthorized: async () => void (await auth.onUnauthorized?.()) } : {}),\n }\n : undefined\n return {\n kind: \"http\",\n label,\n create: () =>\n new StreamableHTTPClientTransport(url, {\n requestInit: { ...options.requestInit, ...(options.headers ? { headers: options.headers } : {}) },\n ...(options.fetch ? { fetch: options.fetch } : {}),\n ...(authProvider ? { authProvider } : {}),\n }),\n }\n}\n","/**\n * `mcpTools(options): Socket` —— 把一台 MCP 服务器接成 reins 的一个 Socket(技术方案 §10,任务 P1)。\n *\n * 形状刻意最小:只用 Socket 的静态贡献 `tools`(异步函数),一个钩子都不挂。\n * - run 起步 `tools/list` 一次 → 每个 MCP 工具翻成 reins `Tool`,整个 run 工具表不变(§9.1 约束 3 / PRD\"不做动态注册\");\n * 服务器中途发 `listChanged` 只影响下一次 run —— 下一次起步再 list 一遍自然拿到新表,循环还会把增删告诉模型(tools_bound)。\n * - `execute` = `tools/call`;结果 content 翻成 ContentPart、`isError` 直通;抛错(未知工具、断连、超时)由循环记成\n * `tool_result(isError)`,循环不崩。\n * - annotations → `risk` 与 `needsApproval` 缺省(readOnly → low;destructive → high + 要审批;其余 medium)。\n * spill / approval / budget 在 afterTool / beforeTool 上自动生效,MCP 服务器不需要知道 reins(P3)。\n * - 配了 `route` 时:`tools/list` 仍走 `transport`(目录连接),每次 `tools/call` 先问宿主要凭据键、按键从连接池取连接\n * (route-pool.ts)。路由不进工具表、不进 configHash。\n */\nimport { defineTool, REINS_VERSION, type Tool } from \"@reinsjs/core\"\nimport { McpConnection } from \"./connection.js\"\nimport { kindOf, type PoolEntry, RoutePool } from \"./route-pool.js\"\nimport { modelToolName, riskOf, toContentParts } from \"./translate.js\"\nimport type { McpToolInfo, McpToolsOptions, McpToolsSocket } from \"./types.js\"\n\nexport const DEFAULT_CALL_TIMEOUT_MS = 60_000\n/** MCP initialize 握手里报给服务器的客户端身份;版本跟随 core,不另维护一份 */\nexport const REINS_MCP_CLIENT_INFO = { name: \"reins\", version: REINS_VERSION }\n\n/**\n * 路由阶段(选凭据、建连握手,还没发出 `tools/call`)run 被中止时给模型的结果。不能让 execute 抛:MCP 工具缺省不可重放,\n * 循环已先写 `tool_started`,中止状态下抛错会被写成\"结果未知\",而调用实际没发出——告诉模型的要与事实一致。\n * 前缀与 core 的\"没执行\"文案同为 `Not executed:`,宿主按前缀判断时口径一致;不复用 `stopTextsOf`:它对非 RunStop 的中止\n * (丢租约等)也说\"被用户停止\"\n */\nexport const ROUTE_NOT_SENT_TEXT =\n \"Not executed: the run was interrupted before this call was sent to the MCP server.\"\n\nexport function mcpTools(options: McpToolsOptions): McpToolsSocket {\n const { transport } = options\n const warn = options.warn ?? ((m: string) => console.warn(m))\n const prefix = options.prefix ?? \"\"\n const timeoutMs = options.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)\n throw new RangeError(\"callTimeoutMs must be a positive number\")\n const route = options.route\n if (route) {\n if (typeof route.keyOf !== \"function\")\n throw new TypeError(`route.keyOf must be a function, got ${kindOf(route.keyOf)}`)\n if (typeof route.transportFor !== \"function\")\n throw new TypeError(`route.transportFor must be a function, got ${kindOf(route.transportFor)}`)\n }\n const connectionOptions = { clientInfo: options.clientInfo ?? REINS_MCP_CLIENT_INFO }\n const conn = new McpConnection(transport, connectionOptions)\n const pool = route ? new RoutePool(route, connectionOptions) : undefined\n const warned = new Set<string>()\n const warnOnce = (key: string, message: string) => {\n if (warned.has(key)) return\n warned.add(key)\n warn(message)\n }\n\n /** 一个 MCP 工具 → reins Tool。名字给模型看的可能被改写,调用时用原名 */\n const toTool = (info: McpToolInfo): Tool => {\n const name = modelToolName(info.name, prefix)\n if (name !== `${prefix}${info.name}`)\n warnOnce(\n `name:${info.name}`,\n `MCP tool name ${info.name} does not meet the model-facing requirements; the name shown to the model is rewritten to ${name}`,\n )\n const risk = riskOf(info.annotations)\n return defineTool<unknown>({\n name,\n description: info.description ?? info.title ?? info.name,\n inputSchema: info.inputSchema,\n risk,\n // 明说破坏性的工具缺省要人点头;循环内置兜底会在没有 Socket 做主时直接转审批\n ...(risk === \"high\" ? { needsApproval: true } : {}),\n async execute(args, ctx) {\n const callOptions = { timeoutMs, ...(ctx.signal ? { signal: ctx.signal } : {}) }\n if (!route || !pool) {\n const result = await conn.callTool(info.name, args, callOptions)\n return { content: toContentParts(result), isError: result.isError === true }\n }\n // 占了池项就必须 release:在途计数挡住 evict 关连接,直到这次调用结束\n let entry: PoolEntry | undefined\n try {\n // 发出前:问宿主要键、取池项、握手。这一段出任何错都意味着调用没发出\n try {\n const key: unknown = await route.keyOf({ name: info.name, args }, ctx)\n if (typeof key !== \"string\" || key === \"\")\n throw new Error(\n `MCP route must return a non-empty credential key for tool ${info.name}, got ${kindOf(key)}; the call was not sent`,\n )\n if (ctx.signal?.aborted) return notSent()\n entry = pool.acquire(key)\n // 新键与 evict 后的第一次调用都要握手:握手期间被中止时请求没发出,SDK 却会在发请求处抛错、被循环写成\"结果未知\"\n await entry.conn.ready()\n if (ctx.signal?.aborted) return notSent()\n } catch (err) {\n if (ctx.signal?.aborted) return notSent()\n throw err\n }\n // 发出\n const result = await entry.conn.callTool(info.name, args, callOptions)\n return { content: toContentParts(result), isError: result.isError === true }\n } finally {\n if (entry) pool.release(entry)\n }\n },\n })\n }\n\n return {\n name: `mcp:${transport.label}`,\n transport,\n tools: async () => {\n let infos: McpToolInfo[]\n try {\n infos = await conn.listTools()\n } catch (err) {\n if (!options.optional) throw err\n warnOnce(\n \"list\",\n `MCP server ${transport.label} is unavailable, so this run carries none of its tools: ${messageOf(err)}`,\n )\n return []\n }\n const tools: Tool[] = []\n for (const info of infos) {\n const tool = toTool(info)\n const overridden = options.override?.(tool, info)\n if (overridden === false) continue\n tools.push(overridden ?? tool)\n }\n return tools\n },\n close: async () => {\n const results = await Promise.allSettled([conn.close(), pool?.closeAll()])\n const failed = results.find((r): r is PromiseRejectedResult => r.status === \"rejected\")\n if (failed) throw failed.reason\n },\n evict: async (key: string) => {\n await pool?.evict(key)\n },\n }\n}\n\nfunction notSent() {\n return { content: [{ type: \"text\" as const, text: ROUTE_NOT_SENT_TEXT }], isError: true }\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * 一条 MCP 连接的生命周期:懒建、跨 run 复用、断了下次需要时按配方重建一次、宿主可关。\n *\n * 为什么不在这里做重连策略(退避、次数):库里的连接是给\"多次 run 复用\"的,一次 `tools/call` 失败就让模型\n * 看到 isError 自己决定要不要再试(宪法一);跨 run 的\"重建一次\"只是把\"上次断了\"这个状态清掉,\n * 不是重试。真要保活、要退避的宿主自己包一层 transport。\n */\nimport { Client, type Transport } from \"@modelcontextprotocol/client\"\nimport type { McpCallResult } from \"./translate.js\"\nimport { toToolInfo } from \"./translate.js\"\nimport { type McpToolInfo, McpToolsError, type McpTransport } from \"./types.js\"\n\nexport interface McpConnectionOptions {\n clientInfo: { name: string; version: string }\n}\n\nexport class McpConnection {\n private client: Client | undefined\n private connecting: Promise<Client> | undefined\n\n constructor(\n readonly transport: McpTransport,\n private readonly options: McpConnectionOptions,\n ) {}\n\n /** 当前是否持有一条活连接(测试与排错用) */\n get connected(): boolean {\n return this.client !== undefined\n }\n\n /** 拿到已连接的 Client:没有就建;正在建就等同一次;上次断了(onclose 已清掉)就重建 */\n private async ensure(): Promise<Client> {\n if (this.client) return this.client\n if (this.connecting) return this.connecting\n this.connecting = (async () => {\n const client = new Client(this.options.clientInfo)\n try {\n await client.connect(this.transport.create() as Transport)\n } catch (err) {\n throw new McpToolsError(\n `Failed to connect to MCP server (${this.transport.label}): ${messageOf(err)}`,\n this.transport.label,\n { cause: err },\n )\n }\n // 传输断开(服务器退出、网络断):清掉引用,下一次 ensure 重建。不在这里自动重连\n client.onclose = () => {\n if (this.client === client) this.client = undefined\n }\n this.client = client\n return client\n })()\n try {\n return await this.connecting\n } finally {\n this.connecting = undefined\n }\n }\n\n /**\n * 确保连接已建好(握手完成)。`route` 把握手放进\"发出前\"那一段:握手期间 run 被中止时请求根本没发出,\n * 调用方据此如实告诉模型\"没发出\",而不是让 SDK 在发请求处抛错、被循环写成\"结果未知\"\n */\n async ready(): Promise<void> {\n await this.ensure()\n }\n\n /** `tools/list`(SDK 会自动翻完全部分页)。绕过 SDK 的列表缓存:每次 run 起步要的就是服务器此刻的表 */\n async listTools(signal?: AbortSignal): Promise<McpToolInfo[]> {\n const client = await this.ensure()\n let result: { tools: unknown[] }\n try {\n result = await client.listTools({}, { cacheMode: \"bypass\", ...(signal ? { signal } : {}) })\n } catch (err) {\n throw new McpToolsError(\n `MCP tools/list failed (${this.transport.label}): ${messageOf(err)}`,\n this.transport.label,\n { cause: err },\n )\n }\n return result.tools.map(toToolInfo)\n }\n\n /** `tools/call`。抛错(未知工具、断连、超时)交给调用方翻成 isError 结果 */\n async callTool(\n name: string,\n args: unknown,\n opts: { signal?: AbortSignal; timeoutMs: number },\n ): Promise<McpCallResult> {\n const client = await this.ensure()\n const result = await client.callTool(\n { name, arguments: (args ?? {}) as Record<string, unknown> },\n { timeout: opts.timeoutMs, ...(opts.signal ? { signal: opts.signal } : {}) },\n )\n return result as McpCallResult\n }\n\n /**\n * 关掉当前连接(宿主热轮换 Socket、进程收尾)。\n * 正在建连时调用:等这次建连有结果再关——否则 `ensure()` 完成后会把新 Client 挂回 `this.client`,\n * 连接泄漏、`onclose` 回调悬挂(2026-09-10 审查修)。建连失败本来就没有连接,吞掉那个错误。\n */\n async close(): Promise<void> {\n if (this.connecting) {\n try {\n await this.connecting\n } catch {\n // 建连失败:没有连接可关\n }\n }\n const client = this.client\n this.client = undefined\n if (client) await client.close()\n }\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * MCP ⇄ reins 的纯函数翻译:工具声明 → `Tool` 的静态部分,`tools/call` 结果 → `ContentPart[]`。\n * 不碰网络、不碰事件,单测直接喂 JSON。\n *\n * 有损的地方都在这里明说(P7):reins 的 ContentPart 只有文本与图片,MCP 的 audio / 二进制 resource\n * 翻成一行说明文字告诉模型\"有这么个东西但看不到\",不静默丢。\n */\nimport type { ContentPart, Tool } from \"@reinsjs/core\"\nimport type { McpToolAnnotations, McpToolInfo } from \"./types.js\"\n\n/** Anthropic / OpenAI 对工具名的共同要求;MCP 没有这个限制,不合规的名字要改写,否则请求 400 */\nexport const MODEL_TOOL_NAME_RE = /^[A-Za-z0-9_-]{1,64}$/\n\n/** 给模型看的名字:加前缀、把不合规字符换成 `_`、截到 64。返回值与原名不同则调用方应告警一次 */\nexport function modelToolName(mcpName: string, prefix = \"\"): string {\n const raw = `${prefix}${mcpName}`\n if (MODEL_TOOL_NAME_RE.test(raw)) return raw\n const cleaned = raw.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 64)\n return cleaned.length > 0 ? cleaned : \"_\"\n}\n\n/**\n * 注解 → 风险档。spec 说注解只是提示、不可信服务器的注解不能当权限依据,所以这里只定**缺省值**:\n * 明说只读 → low;明说破坏性 → high(并缺省要审批);其余(含完全没注解)→ medium,交给 approval 模块的策略。\n * 注意 spec 里 destructiveHint 缺省为 true,我们刻意不把\"没写\"当\"破坏性\"——否则每个 MCP 工具都要审批,\n * 宿主要那么严可以用 `override` 自己定。\n */\nexport function riskOf(annotations: McpToolAnnotations | undefined): NonNullable<Tool[\"risk\"]> {\n if (annotations?.destructiveHint === true) return \"high\"\n if (annotations?.readOnlyHint === true) return \"low\"\n return \"medium\"\n}\n\n/** `tools/list` 里的一项 → 纯数据 McpToolInfo;形状不对就抛(服务器声明不合法,宁可起步失败) */\nexport function toToolInfo(raw: unknown): McpToolInfo {\n if (typeof raw !== \"object\" || raw === null) throw new TypeError(\"MCP tool declaration is not an object\")\n const t = raw as Record<string, unknown>\n if (typeof t.name !== \"string\" || t.name.length === 0)\n throw new TypeError(\"MCP tool declaration has no name\")\n if (typeof t.inputSchema !== \"object\" || t.inputSchema === null)\n throw new TypeError(`MCP tool ${t.name} has no inputSchema`)\n const info: McpToolInfo = { name: t.name, inputSchema: t.inputSchema as Record<string, unknown> }\n if (typeof t.title === \"string\") info.title = t.title\n if (typeof t.description === \"string\") info.description = t.description\n if (typeof t.outputSchema === \"object\" && t.outputSchema !== null)\n info.outputSchema = t.outputSchema as Record<string, unknown>\n if (typeof t.annotations === \"object\" && t.annotations !== null)\n info.annotations = t.annotations as McpToolAnnotations\n return info\n}\n\n/** base64 文本对应的字节数(去掉填充) */\nfunction base64Bytes(b64: string): number {\n const padding = b64.endsWith(\"==\") ? 2 : b64.endsWith(\"=\") ? 1 : 0\n return Math.max(0, Math.floor((b64.length * 3) / 4) - padding)\n}\n\n/** `tools/call` 结果的形状(只取我们用到的字段;SDK 类型不出本包) */\nexport interface McpCallResult {\n content?: unknown\n structuredContent?: unknown\n isError?: unknown\n}\n\n/**\n * MCP 内容块 → reins 内容片段。\n * - text → 文本;image → 图片(mime + base64)\n * - audio → 音频片段(2026-11-05 起;MCP 没有时长,估算走字节折算);缺 data 或 mime 不是 audio/* 时一行说明\n * - resource_link → 一行 \"Resource link: uri (name) [mime]\"\n * - resource(内嵌):文本资源 → 带 uri 头的文本;image/* / video/* / audio/* 二进制 → 对应片段(MCP 没有 video 块,\n * 视频只会从这里来);其他二进制 → 一行说明\n * 模型收不收视频 / 音频由降级层按能力位处置(不收落占位),这里只管如实翻译\n * - 不认识的块 → JSON 文本(不静默丢)\n * - content 为空而有 structuredContent → 其 JSON;都没有 → 空文本(模型总得有个结果块)\n */\nexport function toContentParts(result: McpCallResult): ContentPart[] {\n const blocks = Array.isArray(result.content) ? result.content : []\n const parts: ContentPart[] = []\n for (const raw of blocks) {\n const b = (typeof raw === \"object\" && raw !== null ? raw : {}) as Record<string, unknown>\n switch (b.type) {\n case \"text\":\n parts.push({ type: \"text\", text: typeof b.text === \"string\" ? b.text : \"\" })\n break\n case \"image\":\n if (typeof b.data === \"string\" && typeof b.mimeType === \"string\")\n parts.push({ type: \"image\", mime: b.mimeType, data: b.data })\n else parts.push({ type: \"text\", text: \"[image block without data/mimeType]\" })\n break\n case \"audio\": {\n if (typeof b.data === \"string\" && typeof b.mimeType === \"string\" && b.mimeType.startsWith(\"audio/\")) {\n parts.push({ type: \"audio\", mime: b.mimeType, data: b.data })\n break\n }\n const bytes = typeof b.data === \"string\" ? base64Bytes(b.data) : 0\n parts.push({\n type: \"text\",\n text: `[audio ${String(b.mimeType ?? \"unknown type\")}, ${bytes} bytes; audio cannot be shown to the model]`,\n })\n break\n }\n case \"resource_link\": {\n const name = typeof b.name === \"string\" ? ` (${b.name})` : \"\"\n const mime = typeof b.mimeType === \"string\" ? ` [${b.mimeType}]` : \"\"\n const desc = typeof b.description === \"string\" ? ` — ${b.description}` : \"\"\n parts.push({ type: \"text\", text: `Resource link: ${String(b.uri)}${name}${mime}${desc}` })\n break\n }\n case \"resource\": {\n const r = (typeof b.resource === \"object\" && b.resource !== null ? b.resource : {}) as Record<\n string,\n unknown\n >\n const uri = String(r.uri ?? \"\")\n const mime = typeof r.mimeType === \"string\" ? r.mimeType : undefined\n if (typeof r.text === \"string\") {\n parts.push({ type: \"text\", text: `[resource ${uri}${mime ? ` (${mime})` : \"\"}]\\n${r.text}` })\n } else if (typeof r.blob === \"string\" && mime?.startsWith(\"image/\")) {\n parts.push({ type: \"image\", mime, data: r.blob })\n } else if (typeof r.blob === \"string\" && mime?.startsWith(\"video/\")) {\n parts.push({ type: \"video\", mime, data: r.blob })\n } else if (typeof r.blob === \"string\" && mime?.startsWith(\"audio/\")) {\n parts.push({ type: \"audio\", mime, data: r.blob })\n } else {\n const bytes = typeof r.blob === \"string\" ? base64Bytes(r.blob) : 0\n parts.push({\n type: \"text\",\n text: `[binary resource ${uri}${mime ? ` (${mime})` : \"\"}, ${bytes} bytes; not shown to the model]`,\n })\n }\n break\n }\n default:\n parts.push({ type: \"text\", text: JSON.stringify(raw) ?? String(raw) })\n }\n }\n if (parts.length === 0) {\n if (result.structuredContent !== undefined && result.structuredContent !== null)\n parts.push({ type: \"text\", text: JSON.stringify(result.structuredContent) ?? \"\" })\n else parts.push({ type: \"text\", text: \"\" })\n }\n return parts\n}\n","/**\n * @reinsjs/tools-mcp 的公开类型。MCP SDK 的类型一律不出本包(同降级层对 pi-ai 的约束):\n * 对外只有 reins 自己的 `Tool` / `Socket`,加上这里几个纯数据形状。\n */\nimport type { MaybePromise, Socket, Tool, ToolContext } from \"@reinsjs/core\"\n\n/**\n * 每个请求的 bearer 凭证来源(HTTP 传输)。刻意只有两个方法、且不引用 MCP SDK 的类型:\n * 形状与 SDK 的 `AuthProvider` 结构兼容,宿主不必 import SDK。\n *\n * **不收 SDK 的 `OAuthClientProvider`**:那套的核心是\"开浏览器让人点授权\",在服务端 agent 里跑不通——\n * 令牌该由宿主的 Web 应用先拿好、存起来,循环里只负责取用与刷新。完整 OAuth 流程仍不封装(0.1 立场不变),\n * 宿主要用可以在 `token` / `onUnauthorized` 里自己调 SDK 的 `refreshAuthorization` 等函数。\n */\nexport interface McpAuth {\n /** 每个请求发出前调用。返回 undefined 表示这次不带 Authorization 头 */\n token(): MaybePromise<string | undefined>\n /**\n * 服务器回 401 时调用,之后传输层**自动重试该请求一次**;重试再 401(或没给这个方法)就抛错。\n * 实现里该做的是刷新令牌——下一次 `token()` 要能返回可用的那个\n */\n onUnauthorized?(): MaybePromise<void>\n}\n\n/** MCP 工具注解(spec 里全部是\"提示\",只用来给 risk / needsApproval 定缺省值,不当权限判定) */\nexport interface McpToolAnnotations {\n title?: string\n readOnlyHint?: boolean\n destructiveHint?: boolean\n idempotentHint?: boolean\n openWorldHint?: boolean\n}\n\n/** `tools/list` 返回的一个工具,原样搬过来的纯数据;`override` 钩子拿它做逐工具改写的依据 */\nexport interface McpToolInfo {\n name: string\n title?: string\n description?: string\n inputSchema: Record<string, unknown>\n outputSchema?: Record<string, unknown>\n annotations?: McpToolAnnotations\n}\n\n/**\n * 一条 MCP 传输的\"配方\":怎么建出底层连接。主入口只有 `httpTransport`(Streamable HTTP,纯 Web 标准),\n * `@reinsjs/tools-mcp/node` 才有 `stdioTransport`(起子进程)。连接本身由 `mcpTools()` 懒建、跨 run 复用,\n * 断了在下一次需要时按这个配方重建一次 —— 所以配方必须可重复调用。\n */\nexport interface McpTransport {\n readonly kind: \"http\" | \"stdio\" | \"custom\"\n /** 给 Socket.name、告警与报错用的可读标签(不含密钥) */\n readonly label: string\n /**\n * 建一条新的底层传输。返回值是 MCP SDK 的 Transport,对外按 unknown 处理(SDK 类型不出本包);\n * 自定义传输(如测试用的内存传输)也从这里进\n */\n create(): unknown\n}\n\n/** 一次要路由的调用:MCP 原名(不是给模型看的改写名)与入参(原样交给 `tools/call` 的那份) */\nexport interface McpRoutedCall {\n name: string\n args: unknown\n}\n\n/**\n * 同一台服务器、多份凭据(AdRate 建议 14):工具表仍由 `transport`(目录连接)在 run 起步取一次,\n * 每次 `tools/call` 由宿主选走哪份凭据。前提是各凭据看到的工具表相同(同一份服务端目录)——本包不校验;\n * 某个键的服务器上没有该工具时由服务器报错,按现有规则成 isError。\n *\n * 连接池挂在 Socket 上、只按键区分,Socket 被宿主缓存时就是跨会话、跨用户共享的:\n * `keyOf` 是唯一的授权点(用 `ctx.principal` 判这个人能不能用这个身份),`transportFor` 只能由键决定。\n */\nexport interface McpRoute {\n /**\n * 这次调用走哪份凭据。必须返回非空字符串;返回别的、或抛错 → 本次调用不发出,模型看到 isError\n * (抛错的 message 原样给模型),**绝不回退到目录连接**。每次 execute 调一次(审批续跑后在真正执行时才调)\n */\n keyOf(call: McpRoutedCall, ctx: ToolContext): MaybePromise<string>\n /**\n * 该键的传输配方。每个键在连接池里第一次被用到时调一次,之后连接懒建、跨 run 复用、断了按这份配方重建一次\n * (与 `transport` 同一套语义);凭据换了配方要 `evict(key)` 才会重取。抛错或返回不合规 → 本次调用 isError、不入池\n */\n transportFor(key: string): McpTransport\n}\n\nexport interface McpToolsOptions {\n /** 一台服务器的传输配方。配了 `route` 时它只用于 run 起步的 `tools/list`(目录连接),调用走路由 */\n transport: McpTransport\n /** 按调用选凭据;缺省所有调用走 `transport` */\n route?: McpRoute\n /**\n * 给模型看的工具名前缀(如 `\"gh_\"`),多台服务器同名工具靠它区分;缺省无。\n * 调用时按原名发给服务器。宿主工具与 MCP 工具同名时以宿主为准(core 静态贡献的既有规则)\n */\n prefix?: string\n /** 单次 `tools/call` 超时毫秒,缺省 60_000;到点抛错 → 模型看到 isError 结果,循环不崩 */\n callTimeoutMs?: number\n /**\n * run 起步 `tools/list` 失败时怎么办。缺省 false:抛错,run 在写任何日志之前失败(fail-closed,宿主一定知道)。\n * true:本次 run 不贡献工具、告警一次,模型会从工具变化说明里看到这些工具被移除了\n */\n optional?: boolean\n /**\n * 逐工具改写:调整 needsApproval / risk / resultPolicy / description 等;返回 `false` 即不把这个工具给模型。\n * 入参 `tool` 是按缺省规则翻好的 reins Tool,`info` 是服务器原样的声明\n */\n override?(tool: Tool, info: McpToolInfo): Tool | false | undefined\n /** MCP 握手时的客户端自述,缺省 `{ name: \"reins\", version: <本包版本> }` */\n clientInfo?: { name: string; version: string }\n /** 告警出口(optional 降级、工具名被改写),缺省 console.warn */\n warn?: (message: string) => void\n}\n\nexport interface McpToolsSocket extends Socket {\n readonly transport: McpTransport\n /**\n * 关掉底层连接(含 `route` 连接池里的全部连接,池清空)。进程退出、或宿主按请求重建配置时换掉旧的之前调;\n * 关掉后再跑 run 会按配方重建。收摊语义:不等在途调用\n */\n close(): Promise<void>\n /**\n * 移出 `route` 连接池里某个键的连接(凭据撤销、到期、换了配方):立即移出(之后路由到该键的调用重新调 `transportFor`),\n * 等该连接上在途的调用全部结束再关——不掐断可能已到服务器的写请求;返回的 Promise 关完才 resolve(最长约一到两个 `callTimeoutMs`:在途调用可能还要握手、401 重试一次)。\n * 不存在的键、或没配 route → 无操作\n */\n evict(key: string): Promise<void>\n}\n\n/** 本包抛出的错误:连接建不起来、`tools/list` 失败、服务器声明不合法 */\nexport class McpToolsError extends Error {\n constructor(\n message: string,\n readonly transport: string,\n options?: { cause?: unknown },\n ) {\n super(message, options)\n this.name = \"McpToolsError\"\n }\n}\n","/**\n * `route` 的连接池:同一台服务器、按凭据键各一条连接(AdRate 建议 14,方案 `2026-11-19-MCP按调用选凭据`)。\n *\n * 每个键的连接与目录连接同一套生命周期(懒建、跨 run 复用、断了按配方重建一次),由 `McpConnection` 负责;\n * 本文件只管\"键 → 连接\"与淘汰。两条不变式:\n * - `acquire` 是同步的:取项与在途计数 +1 之间没有 await。否则被 evict 移出的旧项可能在池外被用上,\n * 同一键的并发首调用也会各建一条连接。\n * - evict 不掐断在途调用:SDK 的 `Client.close()` 会中止该传输上在途的 fetch,而此时 run 的 signal 没中止,\n * 循环会写\"失败\",写请求却可能已到服务器——模型一重试就是重复写。所以先移出、等在途归零再关。\n */\nimport { McpConnection, type McpConnectionOptions } from \"./connection.js\"\nimport type { McpRoute, McpTransport } from \"./types.js\"\n\nexport interface PoolEntry {\n readonly conn: McpConnection\n /** 正在这条连接上进行的 `tools/call` 数 */\n inflight: number\n /** 已被 evict 移出、等在途归零后关:归零时调 */\n onDrained?: () => void\n}\n\nexport class RoutePool {\n private readonly entries = new Map<string, PoolEntry>()\n /** 已被 evict 移出、还在等在途归零的项。`closeAll` 收摊时一并关掉,否则它们会拖到 evict 自己关为止 */\n private readonly draining = new Set<PoolEntry>()\n\n constructor(\n private readonly route: McpRoute,\n private readonly options: McpConnectionOptions,\n ) {}\n\n /**\n * 取该键的池项并占一个在途名额(同步,见文件头);调用方必须在 `finally` 里 `release`。\n * 没有就按 `transportFor(key)` 新建;它抛错或返回不合规时不入池,原样抛出(下次再路由到该键会重新调)\n */\n acquire(key: string): PoolEntry {\n let entry = this.entries.get(key)\n if (!entry) {\n const transport = this.route.transportFor(key)\n if (!isTransport(transport))\n throw new TypeError(`route.transportFor must return an McpTransport, got ${kindOf(transport)}`)\n entry = { conn: new McpConnection(transport, this.options), inflight: 0 }\n this.entries.set(key, entry)\n }\n entry.inflight++\n return entry\n }\n\n release(entry: PoolEntry): void {\n entry.inflight--\n if (entry.inflight === 0) entry.onDrained?.()\n }\n\n /** 立即移出,等在途调用结束再关。同一键连调两次时第二次立即返回(项已不在池里) */\n async evict(key: string): Promise<void> {\n const entry = this.entries.get(key)\n if (!entry) return\n this.entries.delete(key)\n this.draining.add(entry)\n try {\n if (entry.inflight > 0)\n await new Promise<void>((resolve) => {\n entry.onDrained = resolve\n })\n await entry.conn.close()\n } finally {\n this.draining.delete(entry)\n }\n }\n\n /**\n * 收摊:关掉池里全部连接(含正在等在途归零的被 evict 项)、清空池,不等在途调用(与 `McpToolsSocket.close` 同义)。\n * 被 evict 项之后在 evict 里再关一次是无操作(`McpConnection.close` 幂等)。全部尝试后有失败抛第一个\n */\n async closeAll(): Promise<void> {\n const conns = [...this.entries.values(), ...this.draining].map((e) => e.conn)\n this.entries.clear()\n const results = await Promise.allSettled(conns.map((c) => c.close()))\n const failed = results.find((r): r is PromiseRejectedResult => r.status === \"rejected\")\n if (failed) throw failed.reason\n }\n}\n\nfunction isTransport(value: unknown): value is McpTransport {\n if (typeof value !== \"object\" || value === null) return false\n const t = value as Record<string, unknown>\n return typeof t.create === \"function\" && typeof t.label === \"string\"\n}\n\n/** 报错文案里的 \"got …\":空串与 null 单独说,其余按 typeof */\nexport function kindOf(value: unknown): string {\n if (value === null) return \"null\"\n if (value === \"\") return \"an empty string\"\n return typeof value\n}\n"],"mappings":";AAOA,SAAS,qCAAqC;AAmB9C,SAAS,uBAAuB,SAAsD;AACpF,MAAI,CAAC,QAAS,QAAO;AACrB,SAAO,OAAO,KAAK,OAAO,EAAE,KAAK,CAAC,MAAM,EAAE,YAAY,MAAM,eAAe;AAC7E;AAEO,SAAS,cAAc,SAA6C;AACzE,MAAI,QAAQ,QAAQ,uBAAuB,QAAQ,OAAO,GAAG;AAC3D,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,QAAM,MAAM,QAAQ,eAAe,MAAM,QAAQ,MAAM,IAAI,IAAI,QAAQ,GAAG;AAE1E,QAAM,QAAQ,GAAG,IAAI,MAAM,GAAG,IAAI,QAAQ;AAE1C,QAAM,OAAO,QAAQ;AACrB,QAAM,eAAe,OACjB;AAAA,IACE,OAAO,YAAY,MAAM,KAAK,MAAM;AAAA,IACpC,GAAI,KAAK,iBAAiB,EAAE,gBAAgB,YAAY,KAAM,MAAM,KAAK,iBAAiB,EAAG,IAAI,CAAC;AAAA,EACpG,IACA;AACJ,SAAO;AAAA,IACL,MAAM;AAAA,IACN;AAAA,IACA,QAAQ,MACN,IAAI,8BAA8B,KAAK;AAAA,MACrC,aAAa,EAAE,GAAG,QAAQ,aAAa,GAAI,QAAQ,UAAU,EAAE,SAAS,QAAQ,QAAQ,IAAI,CA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,EAAE,WAAW,UAAU;AACtF,UAAI,OAAQ,OAAM,OAAO;AAAA,IAC3B;AAAA,IACA,OAAO,OAAO,QAAgB;AAC5B,YAAM,MAAM,MAAM,GAAG;AAAA,IACvB;AAAA,EACF;AACF;AAEA,SAAS,UAAU;AACjB,SAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAiB,MAAM,oBAAoB,CAAC,GAAG,SAAS,KAAK;AAC1F;AAEA,SAASA,WAAU,KAAsB;AACvC,SAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;","names":["messageOf"]}
package/dist/node.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as McpTransport } from './types-F_1Kfslp.js';
1
+ import { a as McpTransport } from './types-JwDpisKk.js';
2
2
  import '@reinsjs/core';
3
3
 
4
4
  interface StdioTransportOptions {
@@ -1,4 +1,4 @@
1
- import { MaybePromise, Tool, Socket } from '@reinsjs/core';
1
+ import { MaybePromise, ToolContext, Tool, Socket } from '@reinsjs/core';
2
2
 
3
3
  /**
4
4
  * @reinsjs/tools-mcp 的公开类型。MCP SDK 的类型一律不出本包(同降级层对 pi-ai 的约束):
@@ -54,8 +54,36 @@ interface McpTransport {
54
54
  */
55
55
  create(): unknown;
56
56
  }
57
+ /** 一次要路由的调用:MCP 原名(不是给模型看的改写名)与入参(原样交给 `tools/call` 的那份) */
58
+ interface McpRoutedCall {
59
+ name: string;
60
+ args: unknown;
61
+ }
62
+ /**
63
+ * 同一台服务器、多份凭据(AdRate 建议 14):工具表仍由 `transport`(目录连接)在 run 起步取一次,
64
+ * 每次 `tools/call` 由宿主选走哪份凭据。前提是各凭据看到的工具表相同(同一份服务端目录)——本包不校验;
65
+ * 某个键的服务器上没有该工具时由服务器报错,按现有规则成 isError。
66
+ *
67
+ * 连接池挂在 Socket 上、只按键区分,Socket 被宿主缓存时就是跨会话、跨用户共享的:
68
+ * `keyOf` 是唯一的授权点(用 `ctx.principal` 判这个人能不能用这个身份),`transportFor` 只能由键决定。
69
+ */
70
+ interface McpRoute {
71
+ /**
72
+ * 这次调用走哪份凭据。必须返回非空字符串;返回别的、或抛错 → 本次调用不发出,模型看到 isError
73
+ * (抛错的 message 原样给模型),**绝不回退到目录连接**。每次 execute 调一次(审批续跑后在真正执行时才调)
74
+ */
75
+ keyOf(call: McpRoutedCall, ctx: ToolContext): MaybePromise<string>;
76
+ /**
77
+ * 该键的传输配方。每个键在连接池里第一次被用到时调一次,之后连接懒建、跨 run 复用、断了按这份配方重建一次
78
+ * (与 `transport` 同一套语义);凭据换了配方要 `evict(key)` 才会重取。抛错或返回不合规 → 本次调用 isError、不入池
79
+ */
80
+ transportFor(key: string): McpTransport;
81
+ }
57
82
  interface McpToolsOptions {
83
+ /** 一台服务器的传输配方。配了 `route` 时它只用于 run 起步的 `tools/list`(目录连接),调用走路由 */
58
84
  transport: McpTransport;
85
+ /** 按调用选凭据;缺省所有调用走 `transport` */
86
+ route?: McpRoute;
59
87
  /**
60
88
  * 给模型看的工具名前缀(如 `"gh_"`),多台服务器同名工具靠它区分;缺省无。
61
89
  * 调用时按原名发给服务器。宿主工具与 MCP 工具同名时以宿主为准(core 静态贡献的既有规则)
@@ -83,8 +111,17 @@ interface McpToolsOptions {
83
111
  }
84
112
  interface McpToolsSocket extends Socket {
85
113
  readonly transport: McpTransport;
86
- /** 关掉底层连接。进程退出、或宿主按请求重建配置时换掉旧的之前调;关掉后再跑 run 会按配方重建 */
114
+ /**
115
+ * 关掉底层连接(含 `route` 连接池里的全部连接,池清空)。进程退出、或宿主按请求重建配置时换掉旧的之前调;
116
+ * 关掉后再跑 run 会按配方重建。收摊语义:不等在途调用
117
+ */
87
118
  close(): Promise<void>;
119
+ /**
120
+ * 移出 `route` 连接池里某个键的连接(凭据撤销、到期、换了配方):立即移出(之后路由到该键的调用重新调 `transportFor`),
121
+ * 等该连接上在途的调用全部结束再关——不掐断可能已到服务器的写请求;返回的 Promise 关完才 resolve(最长约一到两个 `callTimeoutMs`:在途调用可能还要握手、401 重试一次)。
122
+ * 不存在的键、或没配 route → 无操作
123
+ */
124
+ evict(key: string): Promise<void>;
88
125
  }
89
126
  /** 本包抛出的错误:连接建不起来、`tools/list` 失败、服务器声明不合法 */
90
127
  declare class McpToolsError extends Error {
@@ -94,4 +131,4 @@ declare class McpToolsError extends Error {
94
131
  });
95
132
  }
96
133
 
97
- export { type McpAuth as M, type McpTransport as a, type McpToolsOptions as b, type McpToolsSocket as c, type McpToolAnnotations as d, type McpToolInfo as e, McpToolsError as f };
134
+ export { type McpAuth as M, type McpTransport as a, type McpToolsOptions as b, type McpToolsSocket as c, type McpToolAnnotations as d, type McpToolInfo as e, type McpRoute as f, type McpRoutedCall as g, McpToolsError as h };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reinsjs/tools-mcp",
3
- "version": "0.3.10",
3
+ "version": "0.4.0",
4
4
  "description": "reins — MCP servers as a Socket: tools/list once per run, tools/call as Tool.execute, annotations → risk / approval defaults. Streamable HTTP on the Web-standard entry, stdio under ./node",
5
5
  "keywords": [
6
6
  "agent",
@@ -37,13 +37,13 @@
37
37
  ],
38
38
  "dependencies": {
39
39
  "@modelcontextprotocol/client": "2.0.0",
40
- "@reinsjs/core": "0.13.0"
40
+ "@reinsjs/core": "0.14.0"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@modelcontextprotocol/server": "2.0.0",
44
44
  "@types/node": "^22.0.0",
45
45
  "zod": "^4.2.0",
46
- "@reinsjs/brain": "0.8.6"
46
+ "@reinsjs/brain": "0.8.7"
47
47
  },
48
48
  "engines": {
49
49
  "node": ">=22"