@openagentid/mcp 0.1.1 → 0.2.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.
@@ -1 +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;AAG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,OAAA,CAAQ,KAAA,CAAM,KAAK,CAAC,CAAA;AAC5C,IAAA,IAAI,CAAC,EAAE,KAAA,EAAO;AACZ,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"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/types.ts","../src/request-boundary.ts","../src/server.ts","../src/client.ts","../src/skills.ts","../src/workspace.ts"],"names":["AsyncLocalStorage","createHash","randomUUID"],"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,E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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 * Use the workspace adapters for the current SDK. These interfaces also\n * support applications that supply their own signing and verification authority.\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 * Verifier adapter contract — supplied by createWorkspaceMcpServer or an\n * application-owned identity authority.\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 /** Original wire arguments before tool schema defaults/transforms; scopes are derived from parsed arguments. */\n request?: { toolName: string; args: unknown },\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 args?: Record<string, unknown>,\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: Pick<Agent, 'did' | 'verifier'>;\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","import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport interface InboundToolRequest {\n readonly toolName: string;\n readonly args: unknown;\n}\n\ninterface TransportLike {\n onmessage?: (message: unknown, ...extra: unknown[]) => unknown;\n}\n\ninterface Connectable {\n connect?(transport: unknown, ...options: unknown[]): Promise<void>;\n readonly server?: { readonly transport?: unknown };\n}\n\n/** Capture the wire request before McpServer applies the tool's Zod schema.\n * Public transport callbacks are the only boundary touched. Async context keeps\n * concurrent calls isolated even when they reuse a JSON-RPC request ID. */\nexport function installRequestBoundary(server: Connectable): AsyncLocalStorage<InboundToolRequest | undefined> {\n const context = new AsyncLocalStorage<InboundToolRequest | undefined>();\n const wrap = (handler: NonNullable<TransportLike['onmessage']>, transport: object) =>\n (message: unknown, ...extra: unknown[]) => {\n let request: InboundToolRequest | undefined;\n if (message && typeof message === 'object' && 'method' in message && message.method === 'tools/call' &&\n 'params' in message && message.params && typeof message.params === 'object' &&\n 'name' in message.params && typeof message.params.name === 'string') {\n // Snapshot before schemas or application transforms can mutate the input.\n request = { toolName: message.params.name,\n args: structuredClone('arguments' in message.params ? message.params.arguments : undefined) };\n }\n return context.run(request, () => handler.call(transport, message, ...extra));\n };\n\n // Also support wrapping an already-connected McpServer via its public transport.\n const existing = server.server?.transport;\n if (existing && typeof existing === 'object') {\n const transport = existing as TransportLike;\n if (transport.onmessage) transport.onmessage = wrap(transport.onmessage, transport);\n }\n const connect = server.connect;\n if (connect) {\n // Patch the public method so both rawServer.connect() and proxy.connect()\n // work; existing callers need not change which handle they connect.\n server.connect = async function (transport: unknown, ...options: unknown[]) {\n if (!transport || typeof transport !== 'object') throw new TypeError('MCP transport is required');\n const wrapped = new Proxy(transport as TransportLike, {\n set(target, key, value) {\n return Reflect.set(target, key, key === 'onmessage' && typeof value === 'function'\n ? wrap(value as NonNullable<TransportLike['onmessage']>, target) : value, target);\n },\n get(target, key) {\n const value = Reflect.get(target, key, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n await connect.call(this, wrapped, ...options);\n };\n }\n return context;\n}\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';\nimport { installRequestBoundary } from './request-boundary.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 connect?(transport: unknown, ...options: unknown[]): Promise<void>;\n readonly server?: { readonly transport?: 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, installRequestBoundary(server));\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: Pick<Agent, 'did' | 'verifier'>;\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, private readonly requests: ReturnType<typeof installRequestBoundary>) {\n this.agent = config.agent;\n this.requireScopes = config.requireScopes ?? (config.scopeFormat ? tool => [config.scopeFormat!(tool)] : 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 binds the original transmitted request. Authorization policies\n // and tool callbacks intentionally use the SDK's parsed/effective arguments.\n const inbound = this.requests.getStore();\n if (inbound && inbound.toolName !== toolName) throw new Error('MCP request/tool binding mismatch');\n identity = await this.agent.verifier.verify(\n identityEnvelope,\n requiredScopes,\n inbound ?? { toolName, args },\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: Pick<Agent, 'did' | 'signRequest'>;\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: Pick<Agent, 'did' | 'signRequest'>;\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 // Mutate first; the signature must cover the actual transmitted call.\n const replacement = await interceptor.beforeCall?.(params);\n const toSend = await interceptor.signParams(replacement ?? params);\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, params.arguments);\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","import { createHash, randomUUID } from 'node:crypto';\nimport type { OpenAgentWorkspace, LocalChallenge } from '@openagentid/sdk/local';\nimport type { VerifiedAgentIdentity } from '@openagentid/sdk';\nimport type { Agent } from './types.js';\n\nexport interface McpChallengeRequest {\n did: string;\n toolName: string;\n args?: Record<string, unknown>;\n}\n\nfunction canonical(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n const text = JSON.stringify(value);\n if (text === undefined) throw new TypeError('MCP arguments must be JSON values');\n return text;\n }\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical((value as Record<string, unknown>)[key])}`).join(',')}}`;\n}\n\nfunction digest(toolName: string, args: unknown): string {\n return createHash('sha256').update(canonical({ toolName, args: args ?? {} })).digest('hex');\n}\n\n/** Receiver-owned, single-process challenge bindings. Keep this instance alive\n * for the server's lifetime. Restarts fail outstanding requests closed. The SDK\n * persists trust, replay consumption and revocation in the receiver workspace. */\nexport function createWorkspaceMcpServer(options: {\n workspace: OpenAgentWorkspace;\n did: string;\n /** Scopes come from receiver policy, never from request metadata. */\n authorize(identity: VerifiedAgentIdentity): Promise<readonly string[]> | readonly string[];\n maxPendingChallenges?: number;\n}): {\n agent: Pick<Agent, 'did' | 'verifier'>;\n issueChallenge(request: McpChallengeRequest): Promise<LocalChallenge>;\n} {\n const pending = new Map<string, { did: string; digest: string; expiresAt: number }>();\n let issuing = 0;\n const max = options.maxPendingChallenges ?? 1000;\n if (!Number.isSafeInteger(max) || max < 1) throw new TypeError('Invalid pending challenge limit');\n return {\n async issueChallenge(request) {\n for (const [nonce, value] of pending) if (value.expiresAt <= Date.now() / 1000) pending.delete(nonce);\n if (pending.size + issuing >= max) throw new Error('MCP challenge capacity reached');\n const binding = digest(request.toolName, request.args);\n issuing += 1;\n try {\n const challenge = await options.workspace.issueChallenge(request.did);\n pending.set(challenge.nonce, { did: request.did, digest: binding, expiresAt: challenge.expiresAt });\n return challenge;\n } finally { issuing -= 1; }\n },\n agent: {\n did: options.did,\n verifier: {\n async verify(envelope, _scopes, request) {\n const nonce = envelope.nonce;\n const binding = nonce ? pending.get(nonce) : undefined;\n if (!binding || !nonce || !request || binding.did !== envelope.did ||\n binding.expiresAt <= Date.now() / 1000 || binding.digest !== digest(request.toolName, request.args)) {\n throw new Error('MCP challenge does not match this caller and tool request');\n }\n // Claim before awaiting verification to exclude parallel use in this process.\n pending.delete(nonce);\n const proof = JSON.parse(envelope.proof) as Parameters<OpenAgentWorkspace['verify']>[0];\n const identity = await options.workspace.verify(proof, { nonce });\n if (identity.did !== envelope.did) throw new Error('MCP identity DID mismatch');\n const scopes = [...await options.authorize(identity)];\n if (!scopes.every(scope => typeof scope === 'string')) throw new TypeError('Invalid authorized scopes');\n return { did: identity.did, scopes, auditId: randomUUID(), claims: { identity } };\n },\n },\n },\n };\n}\n\n/** Adapt a current SDK signer. Obtain challenges over the receiver's trusted\n * transport; reject an audience change before signing. */\nexport function createWorkspaceMcpClient(options: {\n workspace: OpenAgentWorkspace;\n did: string;\n audience: string;\n issueChallenge(request: McpChallengeRequest): Promise<LocalChallenge>;\n}): Pick<Agent, 'did' | 'signRequest'> {\n return {\n did: options.did,\n async signRequest(toolName, audience, args) {\n if (audience !== undefined && audience !== options.audience) throw new Error('MCP audience mismatch');\n const challenge = await options.issueChallenge({ did: options.did, toolName, ...(args ? { args } : {}) });\n if (challenge.audience !== options.audience || challenge.expiresAt <= Date.now() / 1000) throw new Error('Invalid MCP receiver challenge');\n const proof = await options.workspace.prove(options.did, { audience: options.audience, nonce: challenge.nonce });\n return { did: options.did, proof: JSON.stringify(proof), nonce: challenge.nonce };\n },\n };\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -2,4 +2,36 @@ export { ANONYMOUS_IDENTITY, McpServerLike, withOpenAgent } from './server.cjs';
2
2
  export { McpClientLike, OpenAgentClientConfig, buildIdentityMeta, withOpenAgentClient } from './client.cjs';
3
3
  export { AuthorizationDeniedError, IdentityVerificationError, McpErrorCode, McpErrorCodeValue, MissingIdentityError, OpenAgentMcpError, SkillsPolicyDeniedError } from './errors.cjs';
4
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';
5
+ import { Agent } from './types.cjs';
6
+ export { AuditedResultMeta, Did, ErrorHook, IdentityVerifier, OpenAgentMcpConfig, OpenAgentRequestIdentity, PostCallHook, PreCallHook, ScopeDeriver, SkillsPolicyDecision, SkillsPolicyHook, VerifiedIdentity, defaultRequireScopes, defaultScopeFormat } from './types.cjs';
7
+ import { OpenAgentWorkspace, LocalChallenge } from '@openagentid/sdk/local';
8
+ import { VerifiedAgentIdentity } from '@openagentid/sdk';
9
+
10
+ interface McpChallengeRequest {
11
+ did: string;
12
+ toolName: string;
13
+ args?: Record<string, unknown>;
14
+ }
15
+ /** Receiver-owned, single-process challenge bindings. Keep this instance alive
16
+ * for the server's lifetime. Restarts fail outstanding requests closed. The SDK
17
+ * persists trust, replay consumption and revocation in the receiver workspace. */
18
+ declare function createWorkspaceMcpServer(options: {
19
+ workspace: OpenAgentWorkspace;
20
+ did: string;
21
+ /** Scopes come from receiver policy, never from request metadata. */
22
+ authorize(identity: VerifiedAgentIdentity): Promise<readonly string[]> | readonly string[];
23
+ maxPendingChallenges?: number;
24
+ }): {
25
+ agent: Pick<Agent, 'did' | 'verifier'>;
26
+ issueChallenge(request: McpChallengeRequest): Promise<LocalChallenge>;
27
+ };
28
+ /** Adapt a current SDK signer. Obtain challenges over the receiver's trusted
29
+ * transport; reject an audience change before signing. */
30
+ declare function createWorkspaceMcpClient(options: {
31
+ workspace: OpenAgentWorkspace;
32
+ did: string;
33
+ audience: string;
34
+ issueChallenge(request: McpChallengeRequest): Promise<LocalChallenge>;
35
+ }): Pick<Agent, 'did' | 'signRequest'>;
36
+
37
+ export { Agent, type McpChallengeRequest, createWorkspaceMcpClient, createWorkspaceMcpServer };
package/dist/index.d.ts CHANGED
@@ -2,4 +2,36 @@ export { ANONYMOUS_IDENTITY, McpServerLike, withOpenAgent } from './server.js';
2
2
  export { McpClientLike, OpenAgentClientConfig, buildIdentityMeta, withOpenAgentClient } from './client.js';
3
3
  export { AuthorizationDeniedError, IdentityVerificationError, McpErrorCode, McpErrorCodeValue, MissingIdentityError, OpenAgentMcpError, SkillsPolicyDeniedError } from './errors.js';
4
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';
5
+ import { Agent } from './types.js';
6
+ export { AuditedResultMeta, Did, ErrorHook, IdentityVerifier, OpenAgentMcpConfig, OpenAgentRequestIdentity, PostCallHook, PreCallHook, ScopeDeriver, SkillsPolicyDecision, SkillsPolicyHook, VerifiedIdentity, defaultRequireScopes, defaultScopeFormat } from './types.js';
7
+ import { OpenAgentWorkspace, LocalChallenge } from '@openagentid/sdk/local';
8
+ import { VerifiedAgentIdentity } from '@openagentid/sdk';
9
+
10
+ interface McpChallengeRequest {
11
+ did: string;
12
+ toolName: string;
13
+ args?: Record<string, unknown>;
14
+ }
15
+ /** Receiver-owned, single-process challenge bindings. Keep this instance alive
16
+ * for the server's lifetime. Restarts fail outstanding requests closed. The SDK
17
+ * persists trust, replay consumption and revocation in the receiver workspace. */
18
+ declare function createWorkspaceMcpServer(options: {
19
+ workspace: OpenAgentWorkspace;
20
+ did: string;
21
+ /** Scopes come from receiver policy, never from request metadata. */
22
+ authorize(identity: VerifiedAgentIdentity): Promise<readonly string[]> | readonly string[];
23
+ maxPendingChallenges?: number;
24
+ }): {
25
+ agent: Pick<Agent, 'did' | 'verifier'>;
26
+ issueChallenge(request: McpChallengeRequest): Promise<LocalChallenge>;
27
+ };
28
+ /** Adapt a current SDK signer. Obtain challenges over the receiver's trusted
29
+ * transport; reject an audience change before signing. */
30
+ declare function createWorkspaceMcpClient(options: {
31
+ workspace: OpenAgentWorkspace;
32
+ did: string;
33
+ audience: string;
34
+ issueChallenge(request: McpChallengeRequest): Promise<LocalChallenge>;
35
+ }): Pick<Agent, 'did' | 'signRequest'>;
36
+
37
+ export { Agent, type McpChallengeRequest, createWorkspaceMcpClient, createWorkspaceMcpServer };
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+ import { randomUUID, createHash } from 'crypto';
3
+
1
4
  // src/errors.ts
2
5
  var McpErrorCode = {
3
6
  /** -32600 — request was malformed at the JSON-RPC layer. */
@@ -96,12 +99,47 @@ function formatCause(cause) {
96
99
  // src/types.ts
97
100
  var defaultScopeFormat = (toolName) => `mcp:${toolName}:invoke`;
98
101
  var defaultRequireScopes = (toolName) => [defaultScopeFormat(toolName)];
102
+ function installRequestBoundary(server) {
103
+ const context = new AsyncLocalStorage();
104
+ const wrap = (handler, transport) => (message, ...extra) => {
105
+ let request;
106
+ if (message && typeof message === "object" && "method" in message && message.method === "tools/call" && "params" in message && message.params && typeof message.params === "object" && "name" in message.params && typeof message.params.name === "string") {
107
+ request = {
108
+ toolName: message.params.name,
109
+ args: structuredClone("arguments" in message.params ? message.params.arguments : void 0)
110
+ };
111
+ }
112
+ return context.run(request, () => handler.call(transport, message, ...extra));
113
+ };
114
+ const existing = server.server?.transport;
115
+ if (existing && typeof existing === "object") {
116
+ const transport = existing;
117
+ if (transport.onmessage) transport.onmessage = wrap(transport.onmessage, transport);
118
+ }
119
+ const connect = server.connect;
120
+ if (connect) {
121
+ server.connect = async function(transport, ...options) {
122
+ if (!transport || typeof transport !== "object") throw new TypeError("MCP transport is required");
123
+ const wrapped = new Proxy(transport, {
124
+ set(target, key, value) {
125
+ return Reflect.set(target, key, key === "onmessage" && typeof value === "function" ? wrap(value, target) : value, target);
126
+ },
127
+ get(target, key) {
128
+ const value = Reflect.get(target, key, target);
129
+ return typeof value === "function" ? value.bind(target) : value;
130
+ }
131
+ });
132
+ await connect.call(this, wrapped, ...options);
133
+ };
134
+ }
135
+ return context;
136
+ }
99
137
 
100
138
  // src/server.ts
101
139
  var TOOL_REGISTRATION_METHODS = ["tool", "registerTool"];
102
140
  function withOpenAgent(server, config) {
103
141
  validateConfig(config);
104
- const middleware = new ToolMiddleware(config);
142
+ const middleware = new ToolMiddleware(config, installRequestBoundary(server));
105
143
  return new Proxy(server, {
106
144
  get(target, property, receiver) {
107
145
  const value = Reflect.get(target, property, receiver);
@@ -159,22 +197,24 @@ function findCallbackIndex(args) {
159
197
  return -1;
160
198
  }
161
199
  var ToolMiddleware = class {
162
- agent;
163
- requireScopes;
164
- requireIdentity;
165
- skillsPolicy;
166
- preCall;
167
- postCall;
168
- onError;
169
- constructor(config) {
200
+ constructor(config, requests) {
201
+ this.requests = requests;
170
202
  this.agent = config.agent;
171
- this.requireScopes = config.requireScopes ?? defaultRequireScopes;
203
+ this.requireScopes = config.requireScopes ?? (config.scopeFormat ? (tool) => [config.scopeFormat(tool)] : defaultRequireScopes);
172
204
  this.requireIdentity = config.requireIdentity ?? true;
173
205
  this.skillsPolicy = config.skillsPolicy;
174
206
  this.preCall = config.preCall;
175
207
  this.postCall = config.postCall;
176
208
  this.onError = config.onError;
177
209
  }
210
+ requests;
211
+ agent;
212
+ requireScopes;
213
+ requireIdentity;
214
+ skillsPolicy;
215
+ preCall;
216
+ postCall;
217
+ onError;
178
218
  wrap(toolName, userCallback) {
179
219
  const middleware = this;
180
220
  return async function wrappedCallback(...callbackArgs) {
@@ -222,9 +262,12 @@ var ToolMiddleware = class {
222
262
  const requiredScopes = this.requireScopes(toolName, args);
223
263
  let identity;
224
264
  try {
265
+ const inbound = this.requests.getStore();
266
+ if (inbound && inbound.toolName !== toolName) throw new Error("MCP request/tool binding mismatch");
225
267
  identity = await this.agent.verifier.verify(
226
268
  identityEnvelope,
227
- requiredScopes
269
+ requiredScopes,
270
+ inbound ?? { toolName, args }
228
271
  );
229
272
  } catch (cause) {
230
273
  throw new IdentityVerificationError(toolName, cause);
@@ -369,24 +412,13 @@ var ClientInterceptor = class {
369
412
  wrapCallTool(original, thisArg) {
370
413
  const interceptor = this;
371
414
  return async function wrappedCallTool(params, ...rest) {
372
- const signed = await interceptor.signParams(params);
373
- let toSend = signed;
374
- if (interceptor.beforeCall !== void 0) {
375
- const replacement = await Promise.resolve(
376
- interceptor.beforeCall(signed)
377
- );
378
- if (replacement !== void 0) {
379
- toSend = {
380
- ...replacement,
381
- _meta: replacement._meta ?? signed._meta
382
- };
383
- }
384
- }
415
+ const replacement = await interceptor.beforeCall?.(params);
416
+ const toSend = await interceptor.signParams(replacement ?? params);
385
417
  return original.call(thisArg, toSend, ...rest);
386
418
  };
387
419
  }
388
420
  async signParams(params) {
389
- const identity = await this.agent.signRequest(params.name, this.audience);
421
+ const identity = await this.agent.signRequest(params.name, this.audience, params.arguments);
390
422
  const existingMeta = params._meta ?? {};
391
423
  const existingOpenAgent = typeof existingMeta["openagent"] === "object" && existingMeta["openagent"] !== null ? existingMeta["openagent"] : {};
392
424
  return {
@@ -501,7 +533,71 @@ function combineSkillsPolicies(first, second) {
501
533
  return Promise.resolve(second(input));
502
534
  };
503
535
  }
536
+ function canonical(value) {
537
+ if (value === null || typeof value !== "object") {
538
+ const text = JSON.stringify(value);
539
+ if (text === void 0) throw new TypeError("MCP arguments must be JSON values");
540
+ return text;
541
+ }
542
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
543
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
544
+ }
545
+ function digest(toolName, args) {
546
+ return createHash("sha256").update(canonical({ toolName, args: args ?? {} })).digest("hex");
547
+ }
548
+ function createWorkspaceMcpServer(options) {
549
+ const pending = /* @__PURE__ */ new Map();
550
+ let issuing = 0;
551
+ const max = options.maxPendingChallenges ?? 1e3;
552
+ if (!Number.isSafeInteger(max) || max < 1) throw new TypeError("Invalid pending challenge limit");
553
+ return {
554
+ async issueChallenge(request) {
555
+ for (const [nonce, value] of pending) if (value.expiresAt <= Date.now() / 1e3) pending.delete(nonce);
556
+ if (pending.size + issuing >= max) throw new Error("MCP challenge capacity reached");
557
+ const binding = digest(request.toolName, request.args);
558
+ issuing += 1;
559
+ try {
560
+ const challenge = await options.workspace.issueChallenge(request.did);
561
+ pending.set(challenge.nonce, { did: request.did, digest: binding, expiresAt: challenge.expiresAt });
562
+ return challenge;
563
+ } finally {
564
+ issuing -= 1;
565
+ }
566
+ },
567
+ agent: {
568
+ did: options.did,
569
+ verifier: {
570
+ async verify(envelope, _scopes, request) {
571
+ const nonce = envelope.nonce;
572
+ const binding = nonce ? pending.get(nonce) : void 0;
573
+ if (!binding || !nonce || !request || binding.did !== envelope.did || binding.expiresAt <= Date.now() / 1e3 || binding.digest !== digest(request.toolName, request.args)) {
574
+ throw new Error("MCP challenge does not match this caller and tool request");
575
+ }
576
+ pending.delete(nonce);
577
+ const proof = JSON.parse(envelope.proof);
578
+ const identity = await options.workspace.verify(proof, { nonce });
579
+ if (identity.did !== envelope.did) throw new Error("MCP identity DID mismatch");
580
+ const scopes = [...await options.authorize(identity)];
581
+ if (!scopes.every((scope) => typeof scope === "string")) throw new TypeError("Invalid authorized scopes");
582
+ return { did: identity.did, scopes, auditId: randomUUID(), claims: { identity } };
583
+ }
584
+ }
585
+ }
586
+ };
587
+ }
588
+ function createWorkspaceMcpClient(options) {
589
+ return {
590
+ did: options.did,
591
+ async signRequest(toolName, audience, args) {
592
+ if (audience !== void 0 && audience !== options.audience) throw new Error("MCP audience mismatch");
593
+ const challenge = await options.issueChallenge({ did: options.did, toolName, ...args ? { args } : {} });
594
+ if (challenge.audience !== options.audience || challenge.expiresAt <= Date.now() / 1e3) throw new Error("Invalid MCP receiver challenge");
595
+ const proof = await options.workspace.prove(options.did, { audience: options.audience, nonce: challenge.nonce });
596
+ return { did: options.did, proof: JSON.stringify(proof), nonce: challenge.nonce };
597
+ }
598
+ };
599
+ }
504
600
 
505
- export { ANONYMOUS_IDENTITY, AuthorizationDeniedError, DEFAULT_SKILL_TOOL_NAMES, IdentityVerificationError, InMemorySkillsPolicyStore, McpErrorCode, MissingIdentityError, OpenAgentMcpError, SkillsPolicyDeniedError, buildIdentityMeta, combineSkillsPolicies, createSkillsPolicy, defaultRequireScopes, defaultScopeFormat, withOpenAgent, withOpenAgentClient };
601
+ export { ANONYMOUS_IDENTITY, AuthorizationDeniedError, DEFAULT_SKILL_TOOL_NAMES, IdentityVerificationError, InMemorySkillsPolicyStore, McpErrorCode, MissingIdentityError, OpenAgentMcpError, SkillsPolicyDeniedError, buildIdentityMeta, combineSkillsPolicies, createSkillsPolicy, createWorkspaceMcpClient, createWorkspaceMcpServer, defaultRequireScopes, defaultScopeFormat, withOpenAgent, withOpenAgentClient };
506
602
  //# sourceMappingURL=index.js.map
507
603
  //# sourceMappingURL=index.js.map