@steve31415/baselib 3.28.0 → 3.29.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/README.md CHANGED
@@ -5,7 +5,7 @@ What it provides and why: `docs/SPEC.md`. How it's put together:
5
5
  `docs/IMPL.md`. Full design rationale with alternatives:
6
6
  `~/migration/research/base-services-design.md`.
7
7
 
8
- Server subpath exports: `config`, `log`, `auth`, `oauth-resource`, `s2s`, `db`, `http`, `sync`,
8
+ Server subpath exports: `config`, `log`, `auth`, `oauth-resource`, `connector`, `s2s`, `db`, `http`, `sync`,
9
9
  `app-update`, `llm`, `email`, and `twitter`. Browser exports: `log-browser`, `rum`,
10
10
  `slow-fetch`, `sync-browser`, and `app-update-browser`.
11
11
 
@@ -0,0 +1,149 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
3
+ import type { Tool } from '@modelcontextprotocol/sdk/types.js';
4
+ import type { Hono, MiddlewareHandler } from 'hono';
5
+ import type { z } from 'zod';
6
+ import type { UserAccessPolicy } from './auth.js';
7
+ import type { Logger } from './log-core.js';
8
+ import type { ConnectorUser } from './oauth-resource.js';
9
+ import type { Grants } from './s2s.js';
10
+ export type { ConnectorUser } from './oauth-resource.js';
11
+ /** The headers the front door asserts a user with. */
12
+ export declare const CONNECTOR_HEADERS: {
13
+ readonly user: "x-connector-user";
14
+ readonly role: "x-connector-role";
15
+ readonly scope: "x-connector-scope";
16
+ readonly client: "x-connector-client";
17
+ readonly grant: "x-connector-grant";
18
+ readonly name: "x-connector-name";
19
+ };
20
+ /** The headers that carry `user` to an app (the front door's side). */
21
+ export declare function connectorIdentityHeaders(user: ConnectorUser): Record<string, string>;
22
+ /** The identity the headers assert, or null when any required one is
23
+ * missing or malformed. Header values are what the front door set; an
24
+ * attacker who can set them has already passed the s2s check. */
25
+ export declare function parseConnectorIdentityHeaders(header: (name: string) => string | undefined): ConnectorUser | null;
26
+ export interface ForwardedConnectorOptions {
27
+ /** This app's canonical URL: the audience the front door mints its OIDC
28
+ * token for. */
29
+ audience: string;
30
+ /** The app's checked-in grants; the front door's identity needs `POST /mcp`. */
31
+ grants: Grants;
32
+ /** Which users this app admits — copied from its requireIdentity call. */
33
+ userAccess: UserAccessPolicy;
34
+ logger?: Logger;
35
+ /** Per-caller ceiling for the forwarding service (default 6000/min: one
36
+ * identity carries every user's traffic). */
37
+ rateLimitPerMin?: number;
38
+ }
39
+ /**
40
+ * Admits the front door on an app's `/mcp` and nothing else: the s2s caller
41
+ * must verify and be granted the route (the coding agent always is), then
42
+ * the `X-Connector-*` headers name the user, whose role the app's own access
43
+ * policy is applied to. Sets `c.var.connector`; never `identity`/`user`.
44
+ */
45
+ export declare function requireForwardedConnectorUser(opts: ForwardedConnectorOptions): MiddlewareHandler;
46
+ /** A tool error the model can read and act on. Anything else thrown by a
47
+ * tool is an internal failure: logged at ERROR, answered generically. */
48
+ export declare class ConnectorError extends Error {
49
+ readonly code: string;
50
+ constructor(code: string, message: string);
51
+ }
52
+ /** Content-free facts about one call, for its log line. */
53
+ export type CallFacts = Record<string, string | number | boolean | null>;
54
+ export interface ToolOutcome {
55
+ result: unknown;
56
+ facts: CallFacts;
57
+ }
58
+ export interface ConnectorToolDefinition<Deps, Shape extends z.ZodRawShape = z.ZodRawShape> {
59
+ title: string;
60
+ description: string;
61
+ inputSchema: Shape;
62
+ /** Reads only; needs `<app>:read`. Otherwise `<app>:write`. */
63
+ readOnly: boolean;
64
+ /** A write that overwrites or discards existing content. */
65
+ destructive?: boolean;
66
+ run(deps: Deps, user: ConnectorUser, args: z.infer<z.ZodObject<Shape>>): Promise<ToolOutcome>;
67
+ }
68
+ export interface ConnectorToolTable<Deps> {
69
+ /** The tool-name and scope prefix: `todo` → `todo_*`, `todo:read`. */
70
+ app: string;
71
+ scopes: readonly [read: string, write: string];
72
+ tools: Readonly<Record<string, ConnectorToolDefinition<Deps>>>;
73
+ }
74
+ export declare function connectorScopes(app: string): readonly [string, string];
75
+ /**
76
+ * A typed tool table for one app: `tool()` captures each tool's argument
77
+ * shape; `table()` checks the names and fixes the scopes.
78
+ *
79
+ * const { tool, table } = connectorToolkit<TodoDeps>('todo')
80
+ * export const TOOLS = table({ todo_add_item: tool({ … }) })
81
+ */
82
+ export declare function connectorToolkit<Deps>(app: string): {
83
+ tool<Shape extends z.ZodRawShape>(definition: ConnectorToolDefinition<Deps, Shape>): ConnectorToolDefinition<Deps, Shape>;
84
+ table(tools: Record<string, ConnectorToolDefinition<Deps>>): ConnectorToolTable<Deps>;
85
+ };
86
+ /** The scope a tool needs, or null for a name that is not a tool. */
87
+ export declare function connectorToolScope<Deps>(table: ConnectorToolTable<Deps>, name: unknown): string | null;
88
+ /**
89
+ * The scopes the `tools/call` messages in a JSON-RPC body need. Checked by
90
+ * the route before the SDK runs, because only an HTTP 403 with a challenge —
91
+ * never a tool result — makes the client ask the user for more access.
92
+ */
93
+ export declare function requiredConnectorScopes<Deps>(table: ConnectorToolTable<Deps>, body: unknown): Set<string>;
94
+ export interface ConnectorServerInfo {
95
+ name: string;
96
+ title: string;
97
+ version?: string;
98
+ }
99
+ /**
100
+ * One MCP server per request, bound to the caller: the endpoint is stateless,
101
+ * so nothing is shared between calls or users.
102
+ */
103
+ export declare function buildConnectorServer<Deps>(table: ConnectorToolTable<Deps>, deps: Deps, user: ConnectorUser, logger: Logger, info: ConnectorServerInfo, instructions?: string): McpServer;
104
+ /** Answer one already-parsed JSON-RPC POST for this caller. */
105
+ export declare function handleConnectorRequest(server: McpServer, request: Request, parsedBody: unknown): Promise<Response>;
106
+ /**
107
+ * The table's tool definitions exactly as `tools/list` returns them (the
108
+ * SDK's own JSON Schema rendering), obtained by listing them over an
109
+ * in-memory transport once. Served publicly: definitions are not secret, and
110
+ * the front door merges them into its own `tools/list`.
111
+ */
112
+ export declare function connectorToolDefinitions<Deps>(table: ConnectorToolTable<Deps>, info: ConnectorServerInfo): Promise<Tool[]>;
113
+ /** JSON-RPC bodies are small except for a page of Markdown (apps cap their
114
+ * own content at 1 MiB). */
115
+ export declare const MAX_CONNECTOR_REQUEST_BYTES: number;
116
+ export interface MountConnectorOptions<Deps> extends ForwardedConnectorOptions {
117
+ table: ConnectorToolTable<Deps>;
118
+ deps: Deps;
119
+ logger: Logger;
120
+ serverInfo: ConnectorServerInfo;
121
+ instructions?: string;
122
+ maxRequestBytes?: number;
123
+ /** Replaces the forwarded-identity middleware (a transition hook: Notes
124
+ * admits its old bearer tokens through it for one deploy). Must set
125
+ * `c.var.connector` or answer. */
126
+ admit?: MiddlewareHandler;
127
+ }
128
+ export interface MountedConnector {
129
+ /** The public tool-definition document, as `GET /mcp/tools` serves it. */
130
+ definitions: () => Promise<Tool[]>;
131
+ }
132
+ /**
133
+ * Serve the table at `/mcp` (POST only, forwarded identity, size cap, strict
134
+ * JSON, the scope gate, one server per request) and its definitions at
135
+ * `GET /mcp/tools` (public). Mount before the app's own identity middleware:
136
+ * a connector must never be looked at by `requireIdentity`, and vice versa.
137
+ */
138
+ export declare function mountConnector<Deps>(app: Hono, opts: MountConnectorOptions<Deps>): MountedConnector;
139
+ /**
140
+ * A real MCP client whose HTTP goes straight into a Hono app, for app tests:
141
+ * `headers` carry the caller (`X-Test-S2S-Caller` plus the X-Connector-*
142
+ * identity, or whatever the route's `admit` expects).
143
+ */
144
+ export declare function connectorTestClient(request: (path: string, init: RequestInit) => Response | Promise<Response>, headers: Record<string, string>, path?: string): Promise<Client>;
145
+ /** Call a tool and unpack the JSON text result the kit produces. */
146
+ export declare function callConnectorTool(client: Client, name: string, args: Record<string, unknown>): Promise<{
147
+ isError: boolean;
148
+ value: Record<string, unknown>;
149
+ }>;
@@ -0,0 +1,371 @@
1
+ // The app side of the fleet's AI connector (PW docs/SECURITY.md "Connector
2
+ // access"): everything an app needs to serve its MCP tool table at /mcp,
3
+ // minus the tools themselves.
4
+ //
5
+ // claude.ai talks to one URL, the auth service's front door. The front door
6
+ // verifies the user's OAuth token and relays each tool call to the owning app
7
+ // over the ordinary service-to-service hop: a Google-signed OIDC token for
8
+ // the app's audience, minted as auth's own service account, plus the user's
9
+ // identity in X-Connector-* headers. The user's bearer never reaches an app.
10
+ // So an app's /mcp admits exactly one kind of caller — a granted service
11
+ // asserting a user — and the identity it yields is a `connector`, never
12
+ // `identity`/`user`: a connector cannot reach an app's ordinary routes.
13
+ //
14
+ // Tool names carry the app's prefix (`todo_add_item`): in claude.ai the name
15
+ // is the only thing the model reliably sees, and the front door routes by it.
16
+ // A tool's scope follows from `readOnly`: `<app>:read` or `<app>:write`.
17
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
18
+ import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
19
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
20
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
21
+ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
22
+ import { createMiddleware } from 'hono/factory';
23
+ import { ACCESS_DENIED_CODE, userAllowed } from './auth.js';
24
+ import { serializeError } from './log-core.js';
25
+ import { insufficientScope } from './oauth-resource.js';
26
+ import { RateLimiter, resolveS2sCaller } from './s2s.js';
27
+ // ---------------------------------------------------------------------------
28
+ // The forwarded identity
29
+ /** The headers the front door asserts a user with. */
30
+ export const CONNECTOR_HEADERS = {
31
+ user: 'x-connector-user',
32
+ role: 'x-connector-role',
33
+ scope: 'x-connector-scope',
34
+ client: 'x-connector-client',
35
+ grant: 'x-connector-grant',
36
+ name: 'x-connector-name',
37
+ };
38
+ /** The headers that carry `user` to an app (the front door's side). */
39
+ export function connectorIdentityHeaders(user) {
40
+ return {
41
+ [CONNECTOR_HEADERS.user]: user.email,
42
+ [CONNECTOR_HEADERS.role]: user.role,
43
+ [CONNECTOR_HEADERS.scope]: [...user.scopes].join(' '),
44
+ [CONNECTOR_HEADERS.client]: user.clientId,
45
+ [CONNECTOR_HEADERS.grant]: user.grantId,
46
+ ...(user.name ? { [CONNECTOR_HEADERS.name]: user.name } : {}),
47
+ };
48
+ }
49
+ function parseRole(value) {
50
+ return value === 'owner' || value === 'invited' ? value : undefined;
51
+ }
52
+ /** The identity the headers assert, or null when any required one is
53
+ * missing or malformed. Header values are what the front door set; an
54
+ * attacker who can set them has already passed the s2s check. */
55
+ export function parseConnectorIdentityHeaders(header) {
56
+ const email = header(CONNECTOR_HEADERS.user);
57
+ const role = parseRole(header(CONNECTOR_HEADERS.role));
58
+ const clientId = header(CONNECTOR_HEADERS.client);
59
+ const grantId = header(CONNECTOR_HEADERS.grant);
60
+ const scope = header(CONNECTOR_HEADERS.scope);
61
+ if (!email || !role || !clientId || !grantId || scope === undefined)
62
+ return null;
63
+ const name = header(CONNECTOR_HEADERS.name);
64
+ return {
65
+ type: 'connector',
66
+ email,
67
+ role,
68
+ scopes: new Set(scope.split(' ').filter(Boolean)),
69
+ clientId,
70
+ grantId,
71
+ ...(name ? { name } : {}),
72
+ };
73
+ }
74
+ /**
75
+ * Admits the front door on an app's `/mcp` and nothing else: the s2s caller
76
+ * must verify and be granted the route (the coding agent always is), then
77
+ * the `X-Connector-*` headers name the user, whose role the app's own access
78
+ * policy is applied to. Sets `c.var.connector`; never `identity`/`user`.
79
+ */
80
+ export function requireForwardedConnectorUser(opts) {
81
+ const limiter = new RateLimiter(opts.rateLimitPerMin ?? 6000);
82
+ return createMiddleware(async (c, next) => {
83
+ c.header('cache-control', 'no-store');
84
+ const resolved = await resolveS2sCaller({ audience: opts.audience, grants: opts.grants, logger: opts.logger, limiter }, { authorization: c.req.header('authorization'), testCaller: c.req.header('x-test-s2s-caller') }, c.req.method, c.req.path);
85
+ if (!resolved.caller) {
86
+ const failure = resolved.failure;
87
+ return c.json({ error: failure.error }, failure.status);
88
+ }
89
+ const user = parseConnectorIdentityHeaders((name) => c.req.header(name));
90
+ if (!user) {
91
+ opts.logger?.warn('connector identity headers missing or malformed', {
92
+ caller: resolved.caller.email,
93
+ path: c.req.path,
94
+ });
95
+ return c.json({ error: 'connector identity headers missing' }, 400);
96
+ }
97
+ if (!userAllowed(opts.userAccess, user)) {
98
+ opts.logger?.warn('connector user access denied', {
99
+ email: user.email,
100
+ policy: opts.userAccess,
101
+ path: c.req.path,
102
+ });
103
+ return c.json({ error: 'not enabled for this account', code: ACCESS_DENIED_CODE, email: user.email }, 403);
104
+ }
105
+ c.set('connector', user);
106
+ await next();
107
+ });
108
+ }
109
+ // ---------------------------------------------------------------------------
110
+ // Tool tables
111
+ /** A tool error the model can read and act on. Anything else thrown by a
112
+ * tool is an internal failure: logged at ERROR, answered generically. */
113
+ export class ConnectorError extends Error {
114
+ code;
115
+ constructor(code, message) {
116
+ super(message);
117
+ this.code = code;
118
+ this.name = 'ConnectorError';
119
+ }
120
+ }
121
+ export function connectorScopes(app) {
122
+ return [`${app}:read`, `${app}:write`];
123
+ }
124
+ const APP_NAME = /^[a-z][a-z0-9]*$/;
125
+ const TOOL_NAME = /^[a-z][a-z0-9_]*$/;
126
+ /**
127
+ * A typed tool table for one app: `tool()` captures each tool's argument
128
+ * shape; `table()` checks the names and fixes the scopes.
129
+ *
130
+ * const { tool, table } = connectorToolkit<TodoDeps>('todo')
131
+ * export const TOOLS = table({ todo_add_item: tool({ … }) })
132
+ */
133
+ export function connectorToolkit(app) {
134
+ if (!APP_NAME.test(app))
135
+ throw new Error(`connector app name must be lowercase alphanumeric: ${app}`);
136
+ return {
137
+ tool(definition) {
138
+ return definition;
139
+ },
140
+ table(tools) {
141
+ for (const name of Object.keys(tools)) {
142
+ if (!TOOL_NAME.test(name) || !name.startsWith(`${app}_`)) {
143
+ throw new Error(`connector tool name must be ${app}_<name>: ${name}`);
144
+ }
145
+ }
146
+ return { app, scopes: connectorScopes(app), tools };
147
+ },
148
+ };
149
+ }
150
+ /** The scope a tool needs, or null for a name that is not a tool. */
151
+ export function connectorToolScope(table, name) {
152
+ if (typeof name !== 'string' || !Object.hasOwn(table.tools, name))
153
+ return null;
154
+ return table.tools[name].readOnly ? table.scopes[0] : table.scopes[1];
155
+ }
156
+ /**
157
+ * The scopes the `tools/call` messages in a JSON-RPC body need. Checked by
158
+ * the route before the SDK runs, because only an HTTP 403 with a challenge —
159
+ * never a tool result — makes the client ask the user for more access.
160
+ */
161
+ export function requiredConnectorScopes(table, body) {
162
+ const needed = new Set();
163
+ for (const message of Array.isArray(body) ? body : [body]) {
164
+ if (message === null || typeof message !== 'object')
165
+ continue;
166
+ const { method, params } = message;
167
+ if (method !== 'tools/call')
168
+ continue;
169
+ const scope = connectorToolScope(table, params?.name);
170
+ if (scope !== null)
171
+ needed.add(scope);
172
+ }
173
+ return needed;
174
+ }
175
+ function textResult(value, isError = false) {
176
+ return {
177
+ content: [{ type: 'text', text: JSON.stringify(value) }],
178
+ ...(isError ? { isError: true } : {}),
179
+ };
180
+ }
181
+ /**
182
+ * One MCP server per request, bound to the caller: the endpoint is stateless,
183
+ * so nothing is shared between calls or users.
184
+ */
185
+ export function buildConnectorServer(table, deps, user, logger, info, instructions) {
186
+ const server = new McpServer({ name: info.name, title: info.title, version: info.version ?? '1.0.0' }, instructions ? { instructions } : {});
187
+ for (const [name, definition] of Object.entries(table.tools)) {
188
+ const scope = definition.readOnly ? table.scopes[0] : table.scopes[1];
189
+ server.registerTool(name, {
190
+ title: definition.title,
191
+ description: definition.description,
192
+ inputSchema: definition.inputSchema,
193
+ annotations: {
194
+ readOnlyHint: definition.readOnly,
195
+ ...(definition.readOnly ? {} : { destructiveHint: definition.destructive === true }),
196
+ openWorldHint: false,
197
+ },
198
+ }, async (args) => {
199
+ const started = Date.now();
200
+ // Identifiers, counts and the outcome only — never arguments or
201
+ // results, which are the user's content.
202
+ const log = (outcome, facts) => logger.info('connector tool call', {
203
+ tool: name,
204
+ user: user.email,
205
+ clientId: user.clientId,
206
+ grantId: user.grantId,
207
+ outcome,
208
+ elapsed_ms: Date.now() - started,
209
+ ...facts,
210
+ });
211
+ // The route's scope gate answers 403 first; this holds if it is bypassed.
212
+ if (!user.scopes.has(scope)) {
213
+ log('insufficient_scope', {});
214
+ return textResult({ error: 'insufficient_scope' }, true);
215
+ }
216
+ try {
217
+ const { result, facts } = await definition.run(deps, user, args);
218
+ log('ok', facts);
219
+ return textResult(result);
220
+ }
221
+ catch (error) {
222
+ if (error instanceof ConnectorError) {
223
+ log(error.code, {});
224
+ return textResult({ error: error.code, message: error.message }, true);
225
+ }
226
+ log('internal', {});
227
+ logger.error('connector tool failed', { tool: name, user: user.email, error: serializeError(error) });
228
+ return textResult({ error: 'internal', message: `the ${info.title} server failed to complete this call` }, true);
229
+ }
230
+ });
231
+ }
232
+ return server;
233
+ }
234
+ /** Answer one already-parsed JSON-RPC POST for this caller. */
235
+ export async function handleConnectorRequest(server, request, parsedBody) {
236
+ const transport = new WebStandardStreamableHTTPServerTransport({
237
+ sessionIdGenerator: undefined,
238
+ enableJsonResponse: true,
239
+ });
240
+ try {
241
+ await server.connect(transport);
242
+ return await transport.handleRequest(request, { parsedBody });
243
+ }
244
+ finally {
245
+ await server.close();
246
+ }
247
+ }
248
+ const NO_USER = {
249
+ type: 'connector',
250
+ email: 'definitions@invalid',
251
+ role: 'owner',
252
+ scopes: new Set(),
253
+ clientId: 'definitions',
254
+ grantId: 'definitions',
255
+ };
256
+ const silentLogger = {
257
+ debug: () => { },
258
+ info: () => { },
259
+ warn: () => { },
260
+ error: () => { },
261
+ with: () => silentLogger,
262
+ flush: async () => { },
263
+ };
264
+ /**
265
+ * The table's tool definitions exactly as `tools/list` returns them (the
266
+ * SDK's own JSON Schema rendering), obtained by listing them over an
267
+ * in-memory transport once. Served publicly: definitions are not secret, and
268
+ * the front door merges them into its own `tools/list`.
269
+ */
270
+ export async function connectorToolDefinitions(table, info) {
271
+ const server = buildConnectorServer(table, undefined, NO_USER, silentLogger, info);
272
+ const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
273
+ const client = new Client({ name: 'definitions', version: '0.0.0' });
274
+ try {
275
+ await server.connect(serverSide);
276
+ await client.connect(clientSide);
277
+ return (await client.listTools()).tools;
278
+ }
279
+ finally {
280
+ await client.close();
281
+ await server.close();
282
+ }
283
+ }
284
+ // ---------------------------------------------------------------------------
285
+ // The route
286
+ /** JSON-RPC bodies are small except for a page of Markdown (apps cap their
287
+ * own content at 1 MiB). */
288
+ export const MAX_CONNECTOR_REQUEST_BYTES = 2 * 1024 * 1024;
289
+ /**
290
+ * Serve the table at `/mcp` (POST only, forwarded identity, size cap, strict
291
+ * JSON, the scope gate, one server per request) and its definitions at
292
+ * `GET /mcp/tools` (public). Mount before the app's own identity middleware:
293
+ * a connector must never be looked at by `requireIdentity`, and vice versa.
294
+ */
295
+ export function mountConnector(app, opts) {
296
+ const maxBytes = opts.maxRequestBytes ?? MAX_CONNECTOR_REQUEST_BYTES;
297
+ const admit = opts.admit ?? requireForwardedConnectorUser(opts);
298
+ let definitions;
299
+ const listDefinitions = () => (definitions ??= connectorToolDefinitions(opts.table, opts.serverInfo));
300
+ app.get('/mcp/tools', async (c) => {
301
+ c.header('cache-control', 'no-store');
302
+ return c.json({ tools: await listDefinitions() });
303
+ });
304
+ // Stateless JSON-RPC over POST: no server-initiated stream, no session.
305
+ // Answered before admission, so the SDK client's probe for a stream (a
306
+ // GET) is a plain 405 and not a grants refusal logged at ERROR.
307
+ const postOnly = createMiddleware(async (c, next) => {
308
+ if (c.req.method !== 'POST') {
309
+ c.header('cache-control', 'no-store');
310
+ return c.json({ error: 'method_not_allowed' }, 405, { allow: 'POST' });
311
+ }
312
+ await next();
313
+ });
314
+ app.all('/mcp', postOnly, admit, async (c) => {
315
+ c.header('cache-control', 'no-store');
316
+ const declared = Number(c.req.header('content-length') ?? '0');
317
+ if (!Number.isFinite(declared) || declared > maxBytes) {
318
+ return c.json({ error: 'request_too_large' }, 413);
319
+ }
320
+ const raw = await c.req.arrayBuffer();
321
+ if (raw.byteLength > maxBytes)
322
+ return c.json({ error: 'request_too_large' }, 413);
323
+ let body;
324
+ try {
325
+ body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(raw));
326
+ }
327
+ catch {
328
+ return c.json({ jsonrpc: '2.0', error: { code: -32700, message: 'Parse error' }, id: null }, 400);
329
+ }
330
+ const user = c.get('connector');
331
+ for (const scope of requiredConnectorScopes(opts.table, body)) {
332
+ if (!user.scopes.has(scope)) {
333
+ // The front door rewrites this challenge to its own resource and the
334
+ // scopes it offers; what matters here is the error code.
335
+ return insufficientScope(c, { resource: `${opts.audience}/mcp`, scopes: opts.table.scopes });
336
+ }
337
+ }
338
+ const server = buildConnectorServer(opts.table, opts.deps, user, opts.logger, opts.serverInfo, opts.instructions);
339
+ return handleConnectorRequest(server, c.req.raw, body);
340
+ });
341
+ return { definitions: listDefinitions };
342
+ }
343
+ // ---------------------------------------------------------------------------
344
+ // Test support
345
+ /**
346
+ * A real MCP client whose HTTP goes straight into a Hono app, for app tests:
347
+ * `headers` carry the caller (`X-Test-S2S-Caller` plus the X-Connector-*
348
+ * identity, or whatever the route's `admit` expects).
349
+ */
350
+ export async function connectorTestClient(request, headers, path = '/mcp') {
351
+ const client = new Client({ name: 'connector-test', version: '0.0.0' });
352
+ const transport = new StreamableHTTPClientTransport(new URL(`http://connector.test${path}`), {
353
+ fetch: async (input, init) => {
354
+ const merged = new Headers(init?.headers);
355
+ for (const [name, value] of Object.entries(headers))
356
+ merged.set(name, value);
357
+ return request(new URL(String(input)).pathname, { ...init, headers: merged });
358
+ },
359
+ });
360
+ await client.connect(transport);
361
+ return client;
362
+ }
363
+ /** Call a tool and unpack the JSON text result the kit produces. */
364
+ export async function callConnectorTool(client, name, args) {
365
+ const result = await client.callTool({ name, arguments: args });
366
+ const content = result.content;
367
+ if (content.length !== 1 || content[0].type !== 'text') {
368
+ throw new Error(`unexpected tool result shape for ${name}`);
369
+ }
370
+ return { isError: result.isError === true, value: JSON.parse(content[0].text) };
371
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steve31415/baselib",
3
- "version": "3.28.0",
3
+ "version": "3.29.0",
4
4
  "description": "Plasticine new-world shared platform library: logging, auth, service-to-service auth, db, HTTP, sync, app updates",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -80,6 +80,10 @@
80
80
  "./email": {
81
81
  "types": "./dist/email.d.ts",
82
82
  "default": "./dist/email.js"
83
+ },
84
+ "./connector": {
85
+ "types": "./dist/connector.d.ts",
86
+ "default": "./dist/connector.js"
83
87
  }
84
88
  },
85
89
  "bin": {
@@ -104,10 +108,12 @@
104
108
  "dependencies": {
105
109
  "@google-cloud/cloud-sql-connector": "^1.8.2",
106
110
  "@hono/node-server": "^1.14.0",
111
+ "@modelcontextprotocol/sdk": "^1.32.1",
107
112
  "google-auth-library": "^10.5.0",
108
113
  "hono": "^4.7.0",
109
114
  "pg": "^8.14.0",
110
- "web-vitals": "^6.1.1"
115
+ "web-vitals": "^6.1.1",
116
+ "zod": "^4.6.5"
111
117
  },
112
118
  "devDependencies": {
113
119
  "@types/node": "^22.0.0",