@openagentid/mcp 0.1.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/dist/index.cjs ADDED
@@ -0,0 +1,524 @@
1
+ 'use strict';
2
+
3
+ // src/errors.ts
4
+ var McpErrorCode = {
5
+ /** -32600 — request was malformed at the JSON-RPC layer. */
6
+ InvalidRequest: -32600,
7
+ /** -32601 — the requested method/tool was not found. */
8
+ MethodNotFound: -32601,
9
+ /** -32602 — params failed validation. */
10
+ InvalidParams: -32602,
11
+ /** -32603 — internal server error. */
12
+ InternalError: -32603,
13
+ /** -32000 — generic server error (used for auth failures by default). */
14
+ ServerError: -32e3,
15
+ /** -32001 — identity verification failed. */
16
+ AuthenticationFailed: -32001,
17
+ /** -32002 — caller does not hold the required scope. */
18
+ AuthorizationDenied: -32002,
19
+ /** -32003 — skills policy rejected the call. */
20
+ SkillsPolicyDenied: -32003
21
+ };
22
+ var OpenAgentMcpError = class extends Error {
23
+ code;
24
+ data;
25
+ constructor(message, code, data) {
26
+ super(message);
27
+ this.name = "OpenAgentMcpError";
28
+ this.code = code;
29
+ if (data !== void 0) {
30
+ this.data = data;
31
+ }
32
+ }
33
+ /**
34
+ * Convert to a plain JSON-RPC error payload that the MCP SDK can
35
+ * serialize over the wire.
36
+ */
37
+ toJsonRpcError() {
38
+ if (this.data !== void 0) {
39
+ return { code: this.code, message: this.message, data: this.data };
40
+ }
41
+ return { code: this.code, message: this.message };
42
+ }
43
+ };
44
+ var MissingIdentityError = class extends OpenAgentMcpError {
45
+ constructor(toolName) {
46
+ super(
47
+ `Tool '${toolName}' requires an OpenAgent identity in _meta.openagent.identity`,
48
+ McpErrorCode.AuthenticationFailed,
49
+ { toolName }
50
+ );
51
+ this.name = "MissingIdentityError";
52
+ }
53
+ };
54
+ var IdentityVerificationError = class extends OpenAgentMcpError {
55
+ constructor(toolName, cause) {
56
+ super(
57
+ `Identity verification failed for tool '${toolName}': ${formatCause(cause)}`,
58
+ McpErrorCode.AuthenticationFailed,
59
+ { toolName, cause: formatCause(cause) }
60
+ );
61
+ this.name = "IdentityVerificationError";
62
+ }
63
+ };
64
+ var AuthorizationDeniedError = class extends OpenAgentMcpError {
65
+ constructor(toolName, requiredScopes, heldScopes) {
66
+ super(
67
+ `Tool '${toolName}' requires scopes [${requiredScopes.join(", ")}], caller holds [${heldScopes.join(", ")}]`,
68
+ McpErrorCode.AuthorizationDenied,
69
+ {
70
+ toolName,
71
+ requiredScopes: [...requiredScopes],
72
+ heldScopes: [...heldScopes]
73
+ }
74
+ );
75
+ this.name = "AuthorizationDeniedError";
76
+ }
77
+ };
78
+ var SkillsPolicyDeniedError = class extends OpenAgentMcpError {
79
+ constructor(toolName, reason) {
80
+ super(
81
+ `Skills policy denied tool '${toolName}'${reason ? `: ${reason}` : ""}`,
82
+ McpErrorCode.SkillsPolicyDenied,
83
+ reason !== void 0 ? { toolName, reason } : { toolName }
84
+ );
85
+ this.name = "SkillsPolicyDeniedError";
86
+ }
87
+ };
88
+ function formatCause(cause) {
89
+ if (cause instanceof Error) {
90
+ return cause.message;
91
+ }
92
+ if (typeof cause === "string") {
93
+ return cause;
94
+ }
95
+ return "unknown error";
96
+ }
97
+
98
+ // src/types.ts
99
+ var defaultScopeFormat = (toolName) => `mcp:${toolName}:invoke`;
100
+ var defaultRequireScopes = (toolName) => [defaultScopeFormat(toolName)];
101
+
102
+ // src/server.ts
103
+ var TOOL_REGISTRATION_METHODS = ["tool", "registerTool"];
104
+ function withOpenAgent(server, config) {
105
+ validateConfig(config);
106
+ const middleware = new ToolMiddleware(config);
107
+ return new Proxy(server, {
108
+ get(target, property, receiver) {
109
+ const value = Reflect.get(target, property, receiver);
110
+ if (typeof value !== "function") {
111
+ return value;
112
+ }
113
+ if (typeof property === "string" && TOOL_REGISTRATION_METHODS.includes(property)) {
114
+ return wrapRegistrationMethod(
115
+ value,
116
+ target,
117
+ middleware
118
+ );
119
+ }
120
+ return value.bind(target);
121
+ }
122
+ });
123
+ }
124
+ function validateConfig(config) {
125
+ if (config === null || typeof config !== "object") {
126
+ throw new TypeError("OpenAgentMcpConfig must be an object");
127
+ }
128
+ if (config.agent === void 0 || config.agent === null) {
129
+ throw new TypeError("OpenAgentMcpConfig.agent is required");
130
+ }
131
+ if (config.agent.verifier === void 0 || typeof config.agent.verifier.verify !== "function") {
132
+ throw new TypeError("OpenAgentMcpConfig.agent.verifier.verify is required");
133
+ }
134
+ }
135
+ function wrapRegistrationMethod(original, thisArg, middleware) {
136
+ return function wrapped(...args) {
137
+ const toolName = extractToolName(args);
138
+ const callbackIndex = findCallbackIndex(args);
139
+ if (callbackIndex === -1) {
140
+ return original.apply(thisArg, args);
141
+ }
142
+ const userCallback = args[callbackIndex];
143
+ const wrappedCallback = middleware.wrap(toolName, userCallback);
144
+ const newArgs = [...args];
145
+ newArgs[callbackIndex] = wrappedCallback;
146
+ return original.apply(thisArg, newArgs);
147
+ };
148
+ }
149
+ function extractToolName(args) {
150
+ if (args.length > 0 && typeof args[0] === "string") {
151
+ return args[0];
152
+ }
153
+ return "<unknown>";
154
+ }
155
+ function findCallbackIndex(args) {
156
+ for (let i = args.length - 1; i >= 0; i -= 1) {
157
+ if (typeof args[i] === "function") {
158
+ return i;
159
+ }
160
+ }
161
+ return -1;
162
+ }
163
+ var ToolMiddleware = class {
164
+ agent;
165
+ requireScopes;
166
+ requireIdentity;
167
+ skillsPolicy;
168
+ preCall;
169
+ postCall;
170
+ onError;
171
+ constructor(config) {
172
+ this.agent = config.agent;
173
+ this.requireScopes = config.requireScopes ?? defaultRequireScopes;
174
+ this.requireIdentity = config.requireIdentity ?? true;
175
+ this.skillsPolicy = config.skillsPolicy;
176
+ this.preCall = config.preCall;
177
+ this.postCall = config.postCall;
178
+ this.onError = config.onError;
179
+ }
180
+ wrap(toolName, userCallback) {
181
+ const middleware = this;
182
+ return async function wrappedCallback(...callbackArgs) {
183
+ const { args, extra } = splitToolArgs(callbackArgs);
184
+ const startedAt = nowMs();
185
+ let identity = null;
186
+ try {
187
+ identity = await middleware.runAuthPipeline(toolName, args, extra);
188
+ if (middleware.preCall !== void 0) {
189
+ await middleware.preCall({ toolName, args, identity });
190
+ }
191
+ const result = await Promise.resolve(
192
+ userCallback.apply(this, callbackArgs)
193
+ );
194
+ const stamped = stampAuditMeta(result, identity);
195
+ if (middleware.postCall !== void 0) {
196
+ await middleware.postCall({
197
+ toolName,
198
+ args,
199
+ identity,
200
+ durationMs: nowMs() - startedAt,
201
+ result: stamped
202
+ });
203
+ }
204
+ return stamped;
205
+ } catch (error) {
206
+ if (middleware.onError !== void 0) {
207
+ try {
208
+ await middleware.onError({ toolName, args, identity, error });
209
+ } catch {
210
+ }
211
+ }
212
+ throw normalizeError(error);
213
+ }
214
+ };
215
+ }
216
+ async runAuthPipeline(toolName, args, extra) {
217
+ const identityEnvelope = extractIdentityEnvelope(extra);
218
+ if (identityEnvelope === null) {
219
+ if (this.requireIdentity) {
220
+ throw new MissingIdentityError(toolName);
221
+ }
222
+ return ANONYMOUS_IDENTITY;
223
+ }
224
+ const requiredScopes = this.requireScopes(toolName, args);
225
+ let identity;
226
+ try {
227
+ identity = await this.agent.verifier.verify(
228
+ identityEnvelope,
229
+ requiredScopes
230
+ );
231
+ } catch (cause) {
232
+ throw new IdentityVerificationError(toolName, cause);
233
+ }
234
+ enforceScopes(toolName, requiredScopes, identity.scopes);
235
+ if (this.skillsPolicy !== void 0) {
236
+ const decision = await Promise.resolve(
237
+ this.skillsPolicy({ toolName, args, identity })
238
+ );
239
+ if (!decision.allow) {
240
+ throw new SkillsPolicyDeniedError(toolName, decision.reason);
241
+ }
242
+ }
243
+ return identity;
244
+ }
245
+ };
246
+ function enforceScopes(toolName, required, held) {
247
+ const missing = required.filter((scope) => !held.includes(scope));
248
+ if (missing.length > 0) {
249
+ throw new AuthorizationDeniedError(toolName, required, held);
250
+ }
251
+ }
252
+ function splitToolArgs(callbackArgs) {
253
+ if (callbackArgs.length === 0) {
254
+ return { args: void 0, extra: void 0 };
255
+ }
256
+ if (callbackArgs.length === 1) {
257
+ return { args: void 0, extra: callbackArgs[0] };
258
+ }
259
+ return {
260
+ args: callbackArgs[0],
261
+ extra: callbackArgs[callbackArgs.length - 1]
262
+ };
263
+ }
264
+ function extractIdentityEnvelope(extra) {
265
+ if (extra === null || typeof extra !== "object") {
266
+ return null;
267
+ }
268
+ const meta = extra._meta;
269
+ if (meta === null || typeof meta !== "object") {
270
+ return null;
271
+ }
272
+ const openAgent = meta.openagent;
273
+ if (openAgent === null || typeof openAgent !== "object") {
274
+ return null;
275
+ }
276
+ const identity = openAgent.identity;
277
+ if (identity === null || typeof identity !== "object") {
278
+ return null;
279
+ }
280
+ const candidate = identity;
281
+ if (typeof candidate["did"] !== "string" || typeof candidate["proof"] !== "string") {
282
+ return null;
283
+ }
284
+ const envelope = {
285
+ did: candidate["did"],
286
+ proof: candidate["proof"]
287
+ };
288
+ if (typeof candidate["nonce"] === "string") {
289
+ envelope.nonce = candidate["nonce"];
290
+ }
291
+ if (typeof candidate["context"] === "object" && candidate["context"] !== null) {
292
+ envelope.context = candidate["context"];
293
+ }
294
+ return envelope;
295
+ }
296
+ function stampAuditMeta(result, identity) {
297
+ if (result === null || typeof result !== "object") {
298
+ return result;
299
+ }
300
+ const auditMeta = {
301
+ audit_id: identity.auditId,
302
+ verified_did: identity.did,
303
+ scopes: identity.scopes
304
+ };
305
+ const existingMeta = typeof result._meta === "object" && result._meta !== null ? result._meta : {};
306
+ return {
307
+ ...result,
308
+ _meta: {
309
+ ...existingMeta,
310
+ openagent: auditMeta
311
+ }
312
+ };
313
+ }
314
+ function normalizeError(error) {
315
+ if (error instanceof OpenAgentMcpError) {
316
+ const jsonRpc = error.toJsonRpcError();
317
+ Object.assign(error, { code: jsonRpc.code, data: jsonRpc.data });
318
+ }
319
+ return error;
320
+ }
321
+ function nowMs() {
322
+ if (typeof performance !== "undefined" && typeof performance.now === "function") {
323
+ return performance.now();
324
+ }
325
+ return Date.now();
326
+ }
327
+ var ANONYMOUS_IDENTITY = {
328
+ did: "did:oas:anonymous",
329
+ scopes: [],
330
+ auditId: "anonymous",
331
+ claims: {}
332
+ };
333
+
334
+ // src/client.ts
335
+ function withOpenAgentClient(client, config) {
336
+ if (config === null || typeof config !== "object") {
337
+ throw new TypeError("OpenAgentClientConfig must be an object");
338
+ }
339
+ if (config.agent === void 0 || config.agent === null) {
340
+ throw new TypeError("OpenAgentClientConfig.agent is required");
341
+ }
342
+ if (typeof config.agent.signRequest !== "function") {
343
+ throw new TypeError("OpenAgentClientConfig.agent.signRequest is required");
344
+ }
345
+ const interceptor = new ClientInterceptor(config);
346
+ return new Proxy(client, {
347
+ get(target, property, receiver) {
348
+ const value = Reflect.get(target, property, receiver);
349
+ if (typeof value !== "function") {
350
+ return value;
351
+ }
352
+ if (property === "callTool") {
353
+ return interceptor.wrapCallTool(
354
+ value,
355
+ target
356
+ );
357
+ }
358
+ return value.bind(target);
359
+ }
360
+ });
361
+ }
362
+ var ClientInterceptor = class {
363
+ agent;
364
+ audience;
365
+ beforeCall;
366
+ constructor(config) {
367
+ this.agent = config.agent;
368
+ this.audience = config.audience;
369
+ this.beforeCall = config.beforeCall;
370
+ }
371
+ wrapCallTool(original, thisArg) {
372
+ const interceptor = this;
373
+ return async function wrappedCallTool(params, ...rest) {
374
+ const signed = await interceptor.signParams(params);
375
+ let toSend = signed;
376
+ if (interceptor.beforeCall !== void 0) {
377
+ const replacement = await Promise.resolve(
378
+ interceptor.beforeCall(signed)
379
+ );
380
+ if (replacement !== void 0) {
381
+ toSend = {
382
+ ...replacement,
383
+ _meta: replacement._meta ?? signed._meta
384
+ };
385
+ }
386
+ }
387
+ return original.call(thisArg, toSend, ...rest);
388
+ };
389
+ }
390
+ async signParams(params) {
391
+ const identity = await this.agent.signRequest(params.name, this.audience);
392
+ const existingMeta = params._meta ?? {};
393
+ const existingOpenAgent = typeof existingMeta["openagent"] === "object" && existingMeta["openagent"] !== null ? existingMeta["openagent"] : {};
394
+ return {
395
+ ...params,
396
+ _meta: {
397
+ ...existingMeta,
398
+ openagent: {
399
+ ...existingOpenAgent,
400
+ identity
401
+ }
402
+ }
403
+ };
404
+ }
405
+ };
406
+ function buildIdentityMeta(identity) {
407
+ return {
408
+ openagent: {
409
+ identity: {
410
+ did: identity.did,
411
+ proof: identity.proof,
412
+ ...identity.nonce !== void 0 ? { nonce: identity.nonce } : {},
413
+ ...identity.context !== void 0 ? { context: identity.context } : {}
414
+ }
415
+ }
416
+ };
417
+ }
418
+
419
+ // src/skills.ts
420
+ var DEFAULT_SKILL_TOOL_NAMES = [
421
+ "invoke_skill",
422
+ "run_skill",
423
+ "execute_skill",
424
+ "skill.invoke",
425
+ "skill.run"
426
+ ];
427
+ var InMemorySkillsPolicyStore = class _InMemorySkillsPolicyStore {
428
+ rules;
429
+ constructor(rules = []) {
430
+ this.rules = new Map(rules.map((rule) => [rule.skillName, rule]));
431
+ }
432
+ lookup(skillName) {
433
+ return this.rules.get(skillName) ?? null;
434
+ }
435
+ /** Returns a NEW store with the given rule applied (immutable update). */
436
+ withRule(rule) {
437
+ const next = new Map(this.rules);
438
+ next.set(rule.skillName, rule);
439
+ return new _InMemorySkillsPolicyStore([...next.values()]);
440
+ }
441
+ };
442
+ function createSkillsPolicy(options) {
443
+ const isSkillTool = options.isSkillTool ?? ((toolName) => DEFAULT_SKILL_TOOL_NAMES.includes(toolName));
444
+ const extractSkillName = options.extractSkillName ?? defaultExtractSkillName;
445
+ const defaultDecision = options.defaultDecision ?? {
446
+ allow: true
447
+ };
448
+ return async ({
449
+ toolName,
450
+ args,
451
+ identity
452
+ }) => {
453
+ if (!isSkillTool(toolName)) {
454
+ return defaultDecision;
455
+ }
456
+ const skillName = extractSkillName(args);
457
+ if (skillName === null) {
458
+ return {
459
+ allow: false,
460
+ reason: `Skill tool '${toolName}' invoked without a skill name`
461
+ };
462
+ }
463
+ const rule = await Promise.resolve(options.store.lookup(skillName));
464
+ if (rule === null) {
465
+ return {
466
+ allow: false,
467
+ reason: `No policy entry for skill '${skillName}'`
468
+ };
469
+ }
470
+ if (rule.dids === null) {
471
+ return { allow: true };
472
+ }
473
+ if (rule.dids.includes(identity.did)) {
474
+ return { allow: true };
475
+ }
476
+ return {
477
+ allow: false,
478
+ reason: rule.reason ?? `DID '${identity.did}' is not authorized for skill '${skillName}'`
479
+ };
480
+ };
481
+ }
482
+ function defaultExtractSkillName(args) {
483
+ if (args === null || typeof args !== "object") {
484
+ return null;
485
+ }
486
+ const record = args;
487
+ const skill = record["skill"];
488
+ if (typeof skill === "string" && skill.length > 0) {
489
+ return skill;
490
+ }
491
+ const skillName = record["skillName"];
492
+ if (typeof skillName === "string" && skillName.length > 0) {
493
+ return skillName;
494
+ }
495
+ return null;
496
+ }
497
+ function combineSkillsPolicies(first, second) {
498
+ return async (input) => {
499
+ const a = await Promise.resolve(first(input));
500
+ if (!a.allow) {
501
+ return a;
502
+ }
503
+ return Promise.resolve(second(input));
504
+ };
505
+ }
506
+
507
+ exports.ANONYMOUS_IDENTITY = ANONYMOUS_IDENTITY;
508
+ exports.AuthorizationDeniedError = AuthorizationDeniedError;
509
+ exports.DEFAULT_SKILL_TOOL_NAMES = DEFAULT_SKILL_TOOL_NAMES;
510
+ exports.IdentityVerificationError = IdentityVerificationError;
511
+ exports.InMemorySkillsPolicyStore = InMemorySkillsPolicyStore;
512
+ exports.McpErrorCode = McpErrorCode;
513
+ exports.MissingIdentityError = MissingIdentityError;
514
+ exports.OpenAgentMcpError = OpenAgentMcpError;
515
+ exports.SkillsPolicyDeniedError = SkillsPolicyDeniedError;
516
+ exports.buildIdentityMeta = buildIdentityMeta;
517
+ exports.combineSkillsPolicies = combineSkillsPolicies;
518
+ exports.createSkillsPolicy = createSkillsPolicy;
519
+ exports.defaultRequireScopes = defaultRequireScopes;
520
+ exports.defaultScopeFormat = defaultScopeFormat;
521
+ exports.withOpenAgent = withOpenAgent;
522
+ exports.withOpenAgentClient = withOpenAgentClient;
523
+ //# sourceMappingURL=index.cjs.map
524
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/types.ts","../src/server.ts","../src/client.ts","../src/skills.ts"],"names":[],"mappings":";;;AAUO,IAAM,YAAA,GAAe;AAAA;AAAA,EAE1B,cAAA,EAAgB,MAAA;AAAA;AAAA,EAEhB,cAAA,EAAgB,MAAA;AAAA;AAAA,EAEhB,aAAA,EAAe,MAAA;AAAA;AAAA,EAEf,aAAA,EAAe,MAAA;AAAA;AAAA,EAEf,WAAA,EAAa,KAAA;AAAA;AAAA,EAEb,oBAAA,EAAsB,MAAA;AAAA;AAAA,EAEtB,mBAAA,EAAqB,MAAA;AAAA;AAAA,EAErB,kBAAA,EAAoB;AACtB;AASO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EAC3B,IAAA;AAAA,EACA,IAAA;AAAA,EAEhB,WAAA,CACE,OAAA,EACA,IAAA,EACA,IAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,mBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAI,SAAS,MAAA,EAAW;AACtB,MAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,IACd;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,cAAA,GAIE;AACA,IAAA,IAAI,IAAA,CAAK,SAAS,MAAA,EAAW;AAC3B,MAAA,OAAO,EAAE,MAAM,IAAA,CAAK,IAAA,EAAM,SAAS,IAAA,CAAK,OAAA,EAAS,IAAA,EAAM,IAAA,CAAK,IAAA,EAAK;AAAA,IACnE;AACA,IAAA,OAAO,EAAE,IAAA,EAAM,IAAA,CAAK,IAAA,EAAM,OAAA,EAAS,KAAK,OAAA,EAAQ;AAAA,EAClD;AACF;AAGO,IAAM,oBAAA,GAAN,cAAmC,iBAAA,CAAkB;AAAA,EAC1D,YAAY,QAAA,EAAkB;AAC5B,IAAA,KA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,MAAA,OAAO,CAAA;AAAA,IACT;AACA,IAAA,OAAO,OAAA,CAAQ,OAAA,CAAQ,MAAA,CAAO,KAAK,CAAC,CAAA;AAAA,EACtC,CAAA;AACF","file":"index.cjs","sourcesContent":["/**\n * Error types for @openagentid/mcp.\n *\n * These map onto MCP JSON-RPC error codes so callers see consistent\n * failure modes regardless of which middleware step rejected the call.\n *\n * Reference: https://www.jsonrpc.org/specification#error_object\n */\n\n/** Standard JSON-RPC + MCP error codes used by the middleware. */\nexport const McpErrorCode = {\n /** -32600 — request was malformed at the JSON-RPC layer. */\n InvalidRequest: -32600,\n /** -32601 — the requested method/tool was not found. */\n MethodNotFound: -32601,\n /** -32602 — params failed validation. */\n InvalidParams: -32602,\n /** -32603 — internal server error. */\n InternalError: -32603,\n /** -32000 — generic server error (used for auth failures by default). */\n ServerError: -32000,\n /** -32001 — identity verification failed. */\n AuthenticationFailed: -32001,\n /** -32002 — caller does not hold the required scope. */\n AuthorizationDenied: -32002,\n /** -32003 — skills policy rejected the call. */\n SkillsPolicyDenied: -32003,\n} as const;\n\nexport type McpErrorCodeValue =\n (typeof McpErrorCode)[keyof typeof McpErrorCode];\n\n/**\n * Base class for all middleware errors. Subclasses set a default\n * {@link OpenAgentMcpError.code} that maps to a JSON-RPC error code.\n */\nexport class OpenAgentMcpError extends Error {\n public readonly code: McpErrorCodeValue;\n public readonly data?: Record<string, unknown>;\n\n constructor(\n message: string,\n code: McpErrorCodeValue,\n data?: Record<string, unknown>,\n ) {\n super(message);\n this.name = 'OpenAgentMcpError';\n this.code = code;\n if (data !== undefined) {\n this.data = data;\n }\n }\n\n /**\n * Convert to a plain JSON-RPC error payload that the MCP SDK can\n * serialize over the wire.\n */\n toJsonRpcError(): {\n code: McpErrorCodeValue;\n message: string;\n data?: Record<string, unknown>;\n } {\n if (this.data !== undefined) {\n return { code: this.code, message: this.message, data: this.data };\n }\n return { code: this.code, message: this.message };\n }\n}\n\n/** Caller did not present an OpenAgent identity envelope. */\nexport class MissingIdentityError extends OpenAgentMcpError {\n constructor(toolName: string) {\n super(\n `Tool '${toolName}' requires an OpenAgent identity in _meta.openagent.identity`,\n McpErrorCode.AuthenticationFailed,\n { toolName },\n );\n this.name = 'MissingIdentityError';\n }\n}\n\n/** Identity envelope was present but the verifier rejected it. */\nexport class IdentityVerificationError extends OpenAgentMcpError {\n constructor(toolName: string, cause: unknown) {\n super(\n `Identity verification failed for tool '${toolName}': ${formatCause(cause)}`,\n McpErrorCode.AuthenticationFailed,\n { toolName, cause: formatCause(cause) },\n );\n this.name = 'IdentityVerificationError';\n }\n}\n\n/** Caller's verified identity does not hold the required scopes. */\nexport class AuthorizationDeniedError extends OpenAgentMcpError {\n constructor(\n toolName: string,\n requiredScopes: ReadonlyArray<string>,\n heldScopes: ReadonlyArray<string>,\n ) {\n super(\n `Tool '${toolName}' requires scopes [${requiredScopes.join(', ')}], caller holds [${heldScopes.join(', ')}]`,\n McpErrorCode.AuthorizationDenied,\n {\n toolName,\n requiredScopes: [...requiredScopes],\n heldScopes: [...heldScopes],\n },\n );\n this.name = 'AuthorizationDeniedError';\n }\n}\n\n/** Skills policy hook returned `allow: false`. */\nexport class SkillsPolicyDeniedError extends OpenAgentMcpError {\n constructor(toolName: string, reason: string | undefined) {\n super(\n `Skills policy denied tool '${toolName}'${reason ? `: ${reason}` : ''}`,\n McpErrorCode.SkillsPolicyDenied,\n reason !== undefined ? { toolName, reason } : { toolName },\n );\n this.name = 'SkillsPolicyDeniedError';\n }\n}\n\nfunction formatCause(cause: unknown): string {\n if (cause instanceof Error) {\n return cause.message;\n }\n if (typeof cause === 'string') {\n return cause;\n }\n return 'unknown error';\n}\n","/**\n * Public types for @openagentid/mcp.\n *\n * These interfaces describe the contract the middleware expects from an\n * OpenAgent {@link Agent} instance and the surrounding configuration. They are\n * defined locally so the package can be installed without `@openagentid/sdk` in\n * tests, in CI, and in environments where the host application brings its own\n * verifier implementation.\n *\n * The real `@openagentid/sdk` exports types that are structurally compatible\n * with these — there is no runtime dependency.\n */\n\n/**\n * A decentralized identifier following the `did:oas:*` method or any other\n * DID method understood by the configured verifier.\n */\nexport type Did = string;\n\n/**\n * The four pieces of metadata an MCP request carries about the calling\n * agent. Populated by the {@link createClientInterceptor} on the call site\n * and consumed by the server middleware.\n */\nexport interface OpenAgentRequestIdentity {\n /** Caller's DID — typically `did:oas:...`. */\n did: Did;\n /**\n * A signed challenge response or capability token (Arsenal ACT) the\n * server can verify offline. Format is opaque to the middleware.\n */\n proof: string;\n /**\n * Optional bearer-style nonce. Servers may require it for replay\n * protection. Verifiers MUST treat the value as untrusted until\n * verification succeeds.\n */\n nonce?: string;\n /**\n * Free-form context the verifier may use (issuer DID, audience, scopes\n * the caller claims). Always validated against the verifier's policy.\n */\n context?: Record<string, unknown>;\n}\n\n/**\n * The result of running the auth pipeline against an incoming MCP request.\n * Available to post-call hooks and audit log emitters.\n */\nexport interface VerifiedIdentity {\n did: Did;\n scopes: ReadonlyArray<string>;\n /** Audit identifier echoed back to the caller in result `_meta`. */\n auditId: string;\n /** Verifier-issued claims about the caller. */\n claims: Readonly<Record<string, unknown>>;\n}\n\n/**\n * The verifier interface — implemented by `@openagentid/sdk` (production) and\n * by the in-memory test agent shipped here.\n *\n * Implementations MUST be deterministic for a given input and MUST NOT\n * mutate the request identity object.\n */\nexport interface IdentityVerifier {\n verify(\n identity: OpenAgentRequestIdentity,\n requiredScopes: ReadonlyArray<string>,\n ): Promise<VerifiedIdentity>;\n}\n\n/**\n * Minimal Agent surface — only the parts of the OpenAgent SDK Agent that\n * the MCP middleware actually needs.\n */\nexport interface Agent {\n did: Did;\n verifier: IdentityVerifier;\n /**\n * Sign an outbound MCP call so the receiving server can verify the\n * caller. Returns the identity envelope to attach as `_meta.openagent`.\n */\n signRequest(\n toolName: string,\n audience?: Did,\n ): Promise<OpenAgentRequestIdentity>;\n}\n\n/**\n * Result envelope returned by an authenticated tool call. The `auditId` is\n * pushed into `_meta.openagent.audit_id` on the response, so callers can\n * correlate logs end-to-end.\n */\nexport interface AuditedResultMeta {\n audit_id: string;\n verified_did: Did;\n scopes: ReadonlyArray<string>;\n}\n\n/** Per-tool scope deriver. */\nexport type ScopeDeriver = (\n toolName: string,\n args: unknown,\n) => ReadonlyArray<string>;\n\n/**\n * Hook signature for the skills policy. The hook receives the tool name,\n * the arguments, and the verified identity, and decides whether the call\n * should be allowed.\n */\nexport type SkillsPolicyHook = (input: {\n toolName: string;\n args: unknown;\n identity: VerifiedIdentity;\n}) => Promise<SkillsPolicyDecision> | SkillsPolicyDecision;\n\nexport interface SkillsPolicyDecision {\n allow: boolean;\n reason?: string;\n}\n\n/**\n * Hook fired before a tool body executes — after the identity has been\n * verified and the skills policy has approved the call.\n */\nexport type PreCallHook = (input: {\n toolName: string;\n args: unknown;\n identity: VerifiedIdentity;\n}) => Promise<void> | void;\n\n/**\n * Hook fired after a tool body executes successfully. Use it for audit\n * logging, metrics, and trace propagation. Throwing from this hook does\n * NOT roll back the tool call.\n */\nexport type PostCallHook = (input: {\n toolName: string;\n args: unknown;\n identity: VerifiedIdentity;\n durationMs: number;\n result: unknown;\n}) => Promise<void> | void;\n\n/**\n * Hook fired when the tool body or any earlier middleware step throws.\n * The middleware re-throws the error after running this hook so MCP\n * clients still observe the original failure mode.\n */\nexport type ErrorHook = (input: {\n toolName: string;\n args: unknown;\n identity: VerifiedIdentity | null;\n error: unknown;\n}) => Promise<void> | void;\n\n/**\n * Configuration for {@link withOpenAgent}.\n */\nexport interface OpenAgentMcpConfig {\n /** The agent that owns this MCP server (used for outbound signing). */\n agent: Agent;\n /**\n * Per-tool required scope set. Defaults to\n * `(toolName) => [`mcp:${toolName}:invoke`]`.\n */\n requireScopes?: ScopeDeriver;\n /**\n * If true (default), tool calls without an `_meta.openagent.identity`\n * envelope are rejected. Set to false to opt-in to permissive mode for\n * local development — the middleware will still run hooks but skip\n * verification.\n */\n requireIdentity?: boolean;\n /** Optional skills policy hook. */\n skillsPolicy?: SkillsPolicyHook;\n /** Optional pre-call hook. */\n preCall?: PreCallHook;\n /** Optional post-call hook for audit/log emission. */\n postCall?: PostCallHook;\n /** Optional error hook. */\n onError?: ErrorHook;\n /**\n * Override the default `mcp:<tool>:invoke` scope format. Receives the\n * tool name and returns the canonical scope string.\n */\n scopeFormat?: (toolName: string) => string;\n}\n\n/**\n * Default scope format used when {@link OpenAgentMcpConfig.scopeFormat} is\n * not supplied.\n */\nexport const defaultScopeFormat = (toolName: string): string =>\n `mcp:${toolName}:invoke`;\n\n/**\n * Default scope deriver used when {@link OpenAgentMcpConfig.requireScopes}\n * is not supplied.\n */\nexport const defaultRequireScopes = (toolName: string): ReadonlyArray<string> =>\n [defaultScopeFormat(toolName)];\n","/**\n * Server-side middleware for @openagentid/mcp.\n *\n * Wraps an MCP {@link McpServer} (from `@modelcontextprotocol/sdk`) so that\n * every tool registration runs through an OpenAgent authentication\n * pipeline:\n *\n * 1. Extract the identity envelope from `extra._meta.openagent.identity`.\n * 2. Verify it via the configured {@link IdentityVerifier} and check\n * that the caller holds the scopes returned by `requireScopes`.\n * 3. Run the optional skills policy hook.\n * 4. Run the optional pre-call hook.\n * 5. Invoke the user's tool callback.\n * 6. Run the optional post-call hook with the result + duration.\n * 7. Stamp `audit_id` + `verified_did` into the result `_meta.openagent`.\n * 8. On error, run the optional onError hook and re-throw.\n *\n * Implementation note — version pinning:\n * The middleware is built against `@modelcontextprotocol/sdk@^1.27.0`.\n * The TypeScript SDK changed its tool registration API between 1.17 and\n * 1.27 (`tool(name, cb, ...)` → `registerTool(name, config, cb)`); both\n * call sites are intercepted here so any 1.x server still works.\n *\n * We deliberately do NOT touch the private `_registeredTools` map. The\n * middleware uses a JavaScript {@link Proxy} so callbacks are wrapped\n * exactly once at registration time, before the SDK's internal\n * request handler ever sees them.\n */\n\nimport {\n AuthorizationDeniedError,\n IdentityVerificationError,\n MissingIdentityError,\n OpenAgentMcpError,\n SkillsPolicyDeniedError,\n} from './errors.js';\nimport {\n Agent,\n AuditedResultMeta,\n ErrorHook,\n OpenAgentMcpConfig,\n OpenAgentRequestIdentity,\n PostCallHook,\n PreCallHook,\n ScopeDeriver,\n SkillsPolicyHook,\n VerifiedIdentity,\n defaultRequireScopes,\n} from './types.js';\n\n/**\n * Minimal McpServer surface used by the middleware. We avoid importing\n * concrete types from `@modelcontextprotocol/sdk` because peer-dep\n * versions vary across host applications and the SDK's own type exports\n * are subject to change. The shape below is the intersection of every\n * `1.x` McpServer release.\n */\nexport interface McpServerLike {\n tool(...args: unknown[]): unknown;\n registerTool(...args: unknown[]): unknown;\n}\n\n/**\n * Names of methods on the underlying server that take a tool callback as\n * one of their arguments. Both APIs are intercepted; if the SDK adds new\n * registration methods, append to this list.\n */\nconst TOOL_REGISTRATION_METHODS = ['tool', 'registerTool'] as const;\n\ntype ToolRegistrationMethod = (typeof TOOL_REGISTRATION_METHODS)[number];\n\n/**\n * Wrap an MCP server so every tool call is authenticated against an\n * OpenAgent identity.\n *\n * @example\n * ```ts\n * import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n * import { withOpenAgent } from '@openagentid/mcp';\n * import { agent } from './my-agent.js';\n *\n * const server = new McpServer({ name: 'my-tools', version: '0.1.0' });\n * const authedServer = withOpenAgent(server, { agent });\n *\n * authedServer.tool('search_web', searchHandler);\n * ```\n *\n * The returned proxy is type-compatible with the underlying server, so\n * existing code that calls `tool()`, `registerTool()`, `connect()`, etc.\n * keeps working without changes.\n */\nexport function withOpenAgent<T extends McpServerLike>(\n server: T,\n config: OpenAgentMcpConfig,\n): T {\n validateConfig(config);\n const middleware = new ToolMiddleware(config);\n\n return new Proxy(server, {\n get(target, property, receiver) {\n const value = Reflect.get(target, property, receiver);\n if (typeof value !== 'function') {\n return value;\n }\n if (\n typeof property === 'string' &&\n TOOL_REGISTRATION_METHODS.includes(property as ToolRegistrationMethod)\n ) {\n return wrapRegistrationMethod(\n value as (...args: unknown[]) => unknown,\n target,\n middleware,\n );\n }\n // Bind methods so `this` stays correct when destructured.\n return value.bind(target);\n },\n }) as T;\n}\n\nfunction validateConfig(config: OpenAgentMcpConfig): void {\n if (config === null || typeof config !== 'object') {\n throw new TypeError('OpenAgentMcpConfig must be an object');\n }\n if (config.agent === undefined || config.agent === null) {\n throw new TypeError('OpenAgentMcpConfig.agent is required');\n }\n if (\n config.agent.verifier === undefined ||\n typeof config.agent.verifier.verify !== 'function'\n ) {\n throw new TypeError('OpenAgentMcpConfig.agent.verifier.verify is required');\n }\n}\n\n/**\n * Wrap a single registration method so the user-supplied callback gets\n * replaced by an auth-wrapped one. The MCP SDK accepts the callback in\n * different positional slots depending on overload — we walk the args\n * list and replace the FIRST function we find. This is the same approach\n * the SDK itself uses internally.\n */\nfunction wrapRegistrationMethod(\n original: (...args: unknown[]) => unknown,\n thisArg: unknown,\n middleware: ToolMiddleware,\n): (...args: unknown[]) => unknown {\n return function wrapped(this: unknown, ...args: unknown[]): unknown {\n const toolName = extractToolName(args);\n const callbackIndex = findCallbackIndex(args);\n if (callbackIndex === -1) {\n // No callback in the args — defensive: forward as-is so we don't\n // mask SDK-level errors that the host would otherwise see.\n return original.apply(thisArg, args);\n }\n const userCallback = args[callbackIndex] as (\n ...callbackArgs: unknown[]\n ) => unknown;\n const wrappedCallback = middleware.wrap(toolName, userCallback);\n const newArgs = [...args];\n newArgs[callbackIndex] = wrappedCallback;\n return original.apply(thisArg, newArgs);\n };\n}\n\nfunction extractToolName(args: ReadonlyArray<unknown>): string {\n if (args.length > 0 && typeof args[0] === 'string') {\n return args[0];\n }\n // registerTool's first arg is also a string in 1.27, so this should\n // never trigger — kept as a safety net.\n return '<unknown>';\n}\n\nfunction findCallbackIndex(args: ReadonlyArray<unknown>): number {\n // Walk the args from the end so we find the LAST function — that's\n // the tool body in every overload of both `tool()` and\n // `registerTool()`.\n for (let i = args.length - 1; i >= 0; i -= 1) {\n if (typeof args[i] === 'function') {\n return i;\n }\n }\n return -1;\n}\n\n/**\n * Holds the middleware configuration and wraps individual tool callbacks.\n */\nclass ToolMiddleware {\n private readonly agent: Agent;\n private readonly requireScopes: ScopeDeriver;\n private readonly requireIdentity: boolean;\n private readonly skillsPolicy: SkillsPolicyHook | undefined;\n private readonly preCall: PreCallHook | undefined;\n private readonly postCall: PostCallHook | undefined;\n private readonly onError: ErrorHook | undefined;\n\n constructor(config: OpenAgentMcpConfig) {\n this.agent = config.agent;\n this.requireScopes = config.requireScopes ?? defaultRequireScopes;\n this.requireIdentity = config.requireIdentity ?? true;\n this.skillsPolicy = config.skillsPolicy;\n this.preCall = config.preCall;\n this.postCall = config.postCall;\n this.onError = config.onError;\n }\n\n wrap(\n toolName: string,\n userCallback: (...args: unknown[]) => unknown,\n ): (...args: unknown[]) => Promise<unknown> {\n const middleware = this;\n return async function wrappedCallback(\n this: unknown,\n ...callbackArgs: unknown[]\n ): Promise<unknown> {\n // The MCP SDK invokes tool callbacks in two shapes depending on\n // whether the tool has an input schema:\n // (extra) — no schema\n // (args, extra) — with schema\n // The `extra` is always the LAST arg.\n const { args, extra } = splitToolArgs(callbackArgs);\n const startedAt = nowMs();\n let identity: VerifiedIdentity | null = null;\n\n try {\n identity = await middleware.runAuthPipeline(toolName, args, extra);\n\n if (middleware.preCall !== undefined) {\n await middleware.preCall({ toolName, args, identity });\n }\n\n const result = await Promise.resolve(\n userCallback.apply(this, callbackArgs),\n );\n\n const stamped = stampAuditMeta(result, identity);\n\n if (middleware.postCall !== undefined) {\n await middleware.postCall({\n toolName,\n args,\n identity,\n durationMs: nowMs() - startedAt,\n result: stamped,\n });\n }\n return stamped;\n } catch (error: unknown) {\n if (middleware.onError !== undefined) {\n // The error hook MUST NOT throw — if it does, swallow so the\n // original error propagates to the caller intact.\n try {\n await middleware.onError({ toolName, args, identity, error });\n } catch {\n /* intentionally ignored */\n }\n }\n throw normalizeError(error);\n }\n };\n }\n\n private async runAuthPipeline(\n toolName: string,\n args: unknown,\n extra: unknown,\n ): Promise<VerifiedIdentity> {\n const identityEnvelope = extractIdentityEnvelope(extra);\n if (identityEnvelope === null) {\n if (this.requireIdentity) {\n throw new MissingIdentityError(toolName);\n }\n // Permissive mode: synthesize an \"anonymous\" identity so hooks\n // still run with a stable shape.\n return ANONYMOUS_IDENTITY;\n }\n\n const requiredScopes = this.requireScopes(toolName, args);\n let identity: VerifiedIdentity;\n try {\n identity = await this.agent.verifier.verify(\n identityEnvelope,\n requiredScopes,\n );\n } catch (cause: unknown) {\n throw new IdentityVerificationError(toolName, cause);\n }\n\n enforceScopes(toolName, requiredScopes, identity.scopes);\n\n if (this.skillsPolicy !== undefined) {\n const decision = await Promise.resolve(\n this.skillsPolicy({ toolName, args, identity }),\n );\n if (!decision.allow) {\n throw new SkillsPolicyDeniedError(toolName, decision.reason);\n }\n }\n\n return identity;\n }\n}\n\nfunction enforceScopes(\n toolName: string,\n required: ReadonlyArray<string>,\n held: ReadonlyArray<string>,\n): void {\n const missing = required.filter((scope) => !held.includes(scope));\n if (missing.length > 0) {\n throw new AuthorizationDeniedError(toolName, required, held);\n }\n}\n\nfunction splitToolArgs(callbackArgs: ReadonlyArray<unknown>): {\n args: unknown;\n extra: unknown;\n} {\n if (callbackArgs.length === 0) {\n return { args: undefined, extra: undefined };\n }\n if (callbackArgs.length === 1) {\n // Single argument is the `extra` object.\n return { args: undefined, extra: callbackArgs[0] };\n }\n return {\n args: callbackArgs[0],\n extra: callbackArgs[callbackArgs.length - 1],\n };\n}\n\nfunction extractIdentityEnvelope(\n extra: unknown,\n): OpenAgentRequestIdentity | null {\n if (extra === null || typeof extra !== 'object') {\n return null;\n }\n const meta = (extra as { _meta?: unknown })._meta;\n if (meta === null || typeof meta !== 'object') {\n return null;\n }\n const openAgent = (meta as { openagent?: unknown }).openagent;\n if (openAgent === null || typeof openAgent !== 'object') {\n return null;\n }\n const identity = (openAgent as { identity?: unknown }).identity;\n if (identity === null || typeof identity !== 'object') {\n return null;\n }\n const candidate = identity as Record<string, unknown>;\n if (\n typeof candidate['did'] !== 'string' ||\n typeof candidate['proof'] !== 'string'\n ) {\n return null;\n }\n const envelope: OpenAgentRequestIdentity = {\n did: candidate['did'],\n proof: candidate['proof'],\n };\n if (typeof candidate['nonce'] === 'string') {\n envelope.nonce = candidate['nonce'];\n }\n if (\n typeof candidate['context'] === 'object' &&\n candidate['context'] !== null\n ) {\n envelope.context = candidate['context'] as Record<string, unknown>;\n }\n return envelope;\n}\n\nfunction stampAuditMeta(result: unknown, identity: VerifiedIdentity): unknown {\n if (result === null || typeof result !== 'object') {\n return result;\n }\n const auditMeta: AuditedResultMeta = {\n audit_id: identity.auditId,\n verified_did: identity.did,\n scopes: identity.scopes,\n };\n const existingMeta =\n typeof (result as { _meta?: unknown })._meta === 'object' &&\n (result as { _meta?: unknown })._meta !== null\n ? ((result as { _meta: Record<string, unknown> })._meta)\n : {};\n return {\n ...(result as Record<string, unknown>),\n _meta: {\n ...existingMeta,\n openagent: auditMeta,\n },\n };\n}\n\nfunction normalizeError(error: unknown): unknown {\n if (error instanceof OpenAgentMcpError) {\n // Surface the JSON-RPC code on the error so the SDK's error\n // serializer picks it up.\n const jsonRpc = error.toJsonRpcError();\n Object.assign(error, { code: jsonRpc.code, data: jsonRpc.data });\n }\n return error;\n}\n\nfunction nowMs(): number {\n if (\n typeof performance !== 'undefined' &&\n typeof performance.now === 'function'\n ) {\n return performance.now();\n }\n return Date.now();\n}\n\nconst ANONYMOUS_IDENTITY: VerifiedIdentity = {\n did: 'did:oas:anonymous',\n scopes: [],\n auditId: 'anonymous',\n claims: {},\n};\n\nexport { ANONYMOUS_IDENTITY };\n","/**\n * Client-side interceptor for @openagentid/mcp.\n *\n * Adds an OpenAgent identity envelope (`_meta.openagent.identity`) to\n * outbound MCP `tools/call` requests so an authenticated server can\n * verify the caller. The interceptor wraps the MCP client's `callTool`\n * method via a JavaScript Proxy — the rest of the client surface (list\n * tools, list resources, prompts) is forwarded unchanged.\n *\n * Usage:\n *\n * ```ts\n * import { Client } from '@modelcontextprotocol/sdk/client/index.js';\n * import { withOpenAgentClient } from '@openagentid/mcp/client';\n *\n * const client = new Client({ name: 'my-agent', version: '0.1.0' });\n * const authedClient = withOpenAgentClient(client, { agent });\n *\n * await authedClient.callTool({ name: 'search_web', arguments: { q: 'mcp' } });\n * ```\n */\n\nimport { Agent } from './types.js';\n\n/**\n * Minimal MCP client surface used by the interceptor. Like the server\n * adapter, we describe just the methods we need to keep peer-dep\n * compatibility broad.\n */\nexport interface McpClientLike {\n callTool(\n params: {\n name: string;\n arguments?: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n },\n ...rest: unknown[]\n ): Promise<unknown>;\n}\n\nexport interface OpenAgentClientConfig {\n /** The agent doing the calling — used to sign each request. */\n agent: Agent;\n /**\n * Optional audience DID. When set, it is passed to\n * {@link Agent.signRequest} so the proof can be bound to a specific\n * server. Most production deployments should set this.\n */\n audience?: string;\n /**\n * Optional hook fired before every outbound call. Use it for client-\n * side metrics or to mutate the params (e.g., add tracing headers).\n * Returning a value replaces the params.\n */\n beforeCall?: (params: {\n name: string;\n arguments?: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n }) => Promise<\n | { name: string; arguments?: Record<string, unknown>; _meta?: Record<string, unknown> }\n | void\n > | { name: string; arguments?: Record<string, unknown>; _meta?: Record<string, unknown> }\n | void;\n}\n\n/**\n * Wrap an MCP client so every outbound `callTool` carries an OpenAgent\n * identity envelope.\n */\nexport function withOpenAgentClient<T extends McpClientLike>(\n client: T,\n config: OpenAgentClientConfig,\n): T {\n if (config === null || typeof config !== 'object') {\n throw new TypeError('OpenAgentClientConfig must be an object');\n }\n if (config.agent === undefined || config.agent === null) {\n throw new TypeError('OpenAgentClientConfig.agent is required');\n }\n if (typeof config.agent.signRequest !== 'function') {\n throw new TypeError('OpenAgentClientConfig.agent.signRequest is required');\n }\n\n const interceptor = new ClientInterceptor(config);\n\n return new Proxy(client, {\n get(target, property, receiver) {\n const value = Reflect.get(target, property, receiver);\n if (typeof value !== 'function') {\n return value;\n }\n if (property === 'callTool') {\n return interceptor.wrapCallTool(\n value as McpClientLike['callTool'],\n target,\n );\n }\n return value.bind(target);\n },\n }) as T;\n}\n\nclass ClientInterceptor {\n private readonly agent: Agent;\n private readonly audience: string | undefined;\n private readonly beforeCall: OpenAgentClientConfig['beforeCall'];\n\n constructor(config: OpenAgentClientConfig) {\n this.agent = config.agent;\n this.audience = config.audience;\n this.beforeCall = config.beforeCall;\n }\n\n wrapCallTool(\n original: McpClientLike['callTool'],\n thisArg: unknown,\n ): McpClientLike['callTool'] {\n const interceptor = this;\n return async function wrappedCallTool(\n this: unknown,\n params: {\n name: string;\n arguments?: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n },\n ...rest: unknown[]\n ): Promise<unknown> {\n const signed = await interceptor.signParams(params);\n let toSend: {\n name: string;\n arguments?: Record<string, unknown>;\n _meta: Record<string, unknown>;\n } = signed;\n if (interceptor.beforeCall !== undefined) {\n const replacement = await Promise.resolve(\n interceptor.beforeCall(signed),\n );\n if (replacement !== undefined) {\n // Re-attach the signed _meta if the hook stripped it.\n toSend = {\n ...replacement,\n _meta: replacement._meta ?? signed._meta,\n };\n }\n }\n return original.call(thisArg, toSend, ...rest);\n };\n }\n\n private async signParams(params: {\n name: string;\n arguments?: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n }): Promise<{\n name: string;\n arguments?: Record<string, unknown>;\n _meta: Record<string, unknown>;\n }> {\n const identity = await this.agent.signRequest(params.name, this.audience);\n const existingMeta = params._meta ?? {};\n const existingOpenAgent =\n typeof existingMeta['openagent'] === 'object' &&\n existingMeta['openagent'] !== null\n ? (existingMeta['openagent'] as Record<string, unknown>)\n : {};\n return {\n ...params,\n _meta: {\n ...existingMeta,\n openagent: {\n ...existingOpenAgent,\n identity,\n },\n },\n };\n }\n}\n\n/**\n * Helper for tests and tools that want to construct the identity\n * envelope manually without going through a full Agent. Returns a `_meta`\n * object that can be merged into a CallToolRequest's params.\n */\nexport function buildIdentityMeta(identity: {\n did: string;\n proof: string;\n nonce?: string;\n context?: Record<string, unknown>;\n}): Record<string, unknown> {\n return {\n openagent: {\n identity: {\n did: identity.did,\n proof: identity.proof,\n ...(identity.nonce !== undefined ? { nonce: identity.nonce } : {}),\n ...(identity.context !== undefined\n ? { context: identity.context }\n : {}),\n },\n },\n };\n}\n","/**\n * Skills policy support for @openagentid/mcp.\n *\n * MCP tools and SKILLS.md entries describe the same thing: a capability\n * an agent can invoke. When an MCP server exposes a tool that proxies\n * skill invocation (typically named `invoke_skill` or any name a host\n * application configures), the middleware consults a skills policy\n * before allowing the call. This file provides the helper that picks the\n * right policy for a given call and a small built-in store implementation\n * suitable for tests and reference implementations.\n */\n\nimport { SkillsPolicyDecision, SkillsPolicyHook } from './types.js';\n\n/**\n * Tool name prefixes that the middleware treats as skill-like by default.\n * Host applications can override the matcher entirely via\n * {@link createSkillsPolicy}.\n */\nexport const DEFAULT_SKILL_TOOL_NAMES: ReadonlyArray<string> = [\n 'invoke_skill',\n 'run_skill',\n 'execute_skill',\n 'skill.invoke',\n 'skill.run',\n];\n\n/**\n * A single rule describing whether a `(skillName, did)` pair is allowed.\n * `null` for `dids` means \"any verified caller\". An empty array means\n * \"no caller\".\n */\nexport interface SkillsRule {\n skillName: string;\n /** DIDs allowed to invoke this skill, or `null` for any. */\n dids: ReadonlyArray<string> | null;\n /** Optional reason emitted when the rule denies a call. */\n reason?: string;\n}\n\n/**\n * Policy store interface — implementations may be in-memory, file-backed\n * by `SKILLS.md`, or fetched from a remote service.\n */\nexport interface SkillsPolicyStore {\n lookup(skillName: string): Promise<SkillsRule | null> | SkillsRule | null;\n}\n\n/**\n * Trivial in-memory store useful in tests and as a starting point for\n * production stores.\n */\nexport class InMemorySkillsPolicyStore implements SkillsPolicyStore {\n private readonly rules: Map<string, SkillsRule>;\n\n constructor(rules: ReadonlyArray<SkillsRule> = []) {\n this.rules = new Map(rules.map((rule) => [rule.skillName, rule]));\n }\n\n lookup(skillName: string): SkillsRule | null {\n return this.rules.get(skillName) ?? null;\n }\n\n /** Returns a NEW store with the given rule applied (immutable update). */\n withRule(rule: SkillsRule): InMemorySkillsPolicyStore {\n const next = new Map(this.rules);\n next.set(rule.skillName, rule);\n return new InMemorySkillsPolicyStore([...next.values()]);\n }\n}\n\nexport interface CreateSkillsPolicyOptions {\n /** The store backing skill lookups. */\n store: SkillsPolicyStore;\n /**\n * Returns true when a tool call should be checked against the skills\n * policy. Defaults to matching the tool name against\n * {@link DEFAULT_SKILL_TOOL_NAMES}.\n */\n isSkillTool?: (toolName: string) => boolean;\n /**\n * Extracts the skill name from the tool's arguments. Defaults to\n * reading `args.skill` or `args.skillName`.\n */\n extractSkillName?: (args: unknown) => string | null;\n /**\n * Default decision when no rule matches. Defaults to `{ allow: true }`\n * to keep non-skill tools unaffected.\n */\n defaultDecision?: SkillsPolicyDecision;\n}\n\n/**\n * Build a {@link SkillsPolicyHook} from a store and matching options.\n *\n * The returned hook always allows tools that are not skill-like; it only\n * consults the store when {@link CreateSkillsPolicyOptions.isSkillTool}\n * returns true.\n */\nexport function createSkillsPolicy(\n options: CreateSkillsPolicyOptions,\n): SkillsPolicyHook {\n const isSkillTool =\n options.isSkillTool ??\n ((toolName: string) => DEFAULT_SKILL_TOOL_NAMES.includes(toolName));\n const extractSkillName =\n options.extractSkillName ?? defaultExtractSkillName;\n const defaultDecision: SkillsPolicyDecision = options.defaultDecision ?? {\n allow: true,\n };\n\n return async ({\n toolName,\n args,\n identity,\n }): Promise<SkillsPolicyDecision> => {\n if (!isSkillTool(toolName)) {\n return defaultDecision;\n }\n\n const skillName = extractSkillName(args);\n if (skillName === null) {\n return {\n allow: false,\n reason: `Skill tool '${toolName}' invoked without a skill name`,\n };\n }\n\n const rule = await Promise.resolve(options.store.lookup(skillName));\n if (rule === null) {\n return {\n allow: false,\n reason: `No policy entry for skill '${skillName}'`,\n };\n }\n\n if (rule.dids === null) {\n return { allow: true };\n }\n\n if (rule.dids.includes(identity.did)) {\n return { allow: true };\n }\n\n return {\n allow: false,\n reason:\n rule.reason ??\n `DID '${identity.did}' is not authorized for skill '${skillName}'`,\n };\n };\n}\n\nfunction defaultExtractSkillName(args: unknown): string | null {\n if (args === null || typeof args !== 'object') {\n return null;\n }\n const record = args as Record<string, unknown>;\n const skill = record['skill'];\n if (typeof skill === 'string' && skill.length > 0) {\n return skill;\n }\n const skillName = record['skillName'];\n if (typeof skillName === 'string' && skillName.length > 0) {\n return skillName;\n }\n return null;\n}\n\n/**\n * Compose two skills policy hooks. The combined hook denies if either\n * underlying hook denies; allow decisions from `first` are forwarded to\n * `second`.\n */\nexport function combineSkillsPolicies(\n first: SkillsPolicyHook,\n second: SkillsPolicyHook,\n): SkillsPolicyHook {\n return async (input): Promise<SkillsPolicyDecision> => {\n const a = await Promise.resolve(first(input));\n if (!a.allow) {\n return a;\n }\n return Promise.resolve(second(input));\n };\n}\n\n/** Re-exported for convenience. */\nexport type {\n SkillsPolicyHook,\n SkillsPolicyDecision,\n VerifiedIdentity,\n} from './types.js';\n"]}
@@ -0,0 +1,5 @@
1
+ export { ANONYMOUS_IDENTITY, McpServerLike, withOpenAgent } from './server.cjs';
2
+ export { McpClientLike, OpenAgentClientConfig, buildIdentityMeta, withOpenAgentClient } from './client.cjs';
3
+ export { AuthorizationDeniedError, IdentityVerificationError, McpErrorCode, McpErrorCodeValue, MissingIdentityError, OpenAgentMcpError, SkillsPolicyDeniedError } from './errors.cjs';
4
+ export { CreateSkillsPolicyOptions, DEFAULT_SKILL_TOOL_NAMES, InMemorySkillsPolicyStore, SkillsPolicyStore, SkillsRule, combineSkillsPolicies, createSkillsPolicy } from './skills.cjs';
5
+ export { Agent, AuditedResultMeta, Did, ErrorHook, IdentityVerifier, OpenAgentMcpConfig, OpenAgentRequestIdentity, PostCallHook, PreCallHook, ScopeDeriver, SkillsPolicyDecision, SkillsPolicyHook, VerifiedIdentity, defaultRequireScopes, defaultScopeFormat } from './types.cjs';
@@ -0,0 +1,5 @@
1
+ export { ANONYMOUS_IDENTITY, McpServerLike, withOpenAgent } from './server.js';
2
+ export { McpClientLike, OpenAgentClientConfig, buildIdentityMeta, withOpenAgentClient } from './client.js';
3
+ export { AuthorizationDeniedError, IdentityVerificationError, McpErrorCode, McpErrorCodeValue, MissingIdentityError, OpenAgentMcpError, SkillsPolicyDeniedError } from './errors.js';
4
+ export { CreateSkillsPolicyOptions, DEFAULT_SKILL_TOOL_NAMES, InMemorySkillsPolicyStore, SkillsPolicyStore, SkillsRule, combineSkillsPolicies, createSkillsPolicy } from './skills.js';
5
+ export { Agent, AuditedResultMeta, Did, ErrorHook, IdentityVerifier, OpenAgentMcpConfig, OpenAgentRequestIdentity, PostCallHook, PreCallHook, ScopeDeriver, SkillsPolicyDecision, SkillsPolicyHook, VerifiedIdentity, defaultRequireScopes, defaultScopeFormat } from './types.js';