@nevermined-io/payments 1.12.0 → 1.14.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.
Files changed (98) hide show
  1. package/README.md +33 -0
  2. package/dist/a2a/clientRegistry.d.ts +10 -1
  3. package/dist/a2a/clientRegistry.d.ts.map +1 -1
  4. package/dist/a2a/clientRegistry.js +13 -4
  5. package/dist/a2a/clientRegistry.js.map +1 -1
  6. package/dist/a2a/paymentsClient.d.ts +60 -3
  7. package/dist/a2a/paymentsClient.d.ts.map +1 -1
  8. package/dist/a2a/paymentsClient.js +129 -8
  9. package/dist/a2a/paymentsClient.js.map +1 -1
  10. package/dist/a2a/paymentsRequestHandler.d.ts +5 -1
  11. package/dist/a2a/paymentsRequestHandler.d.ts.map +1 -1
  12. package/dist/a2a/paymentsRequestHandler.js +156 -13
  13. package/dist/a2a/paymentsRequestHandler.js.map +1 -1
  14. package/dist/a2a/types.d.ts +30 -0
  15. package/dist/a2a/types.d.ts.map +1 -1
  16. package/dist/a2a/types.js.map +1 -1
  17. package/dist/api/agents-api.d.ts +4 -3
  18. package/dist/api/agents-api.d.ts.map +1 -1
  19. package/dist/api/agents-api.js +7 -4
  20. package/dist/api/agents-api.js.map +1 -1
  21. package/dist/api/base-payments.d.ts +7 -2
  22. package/dist/api/base-payments.d.ts.map +1 -1
  23. package/dist/api/base-payments.js +15 -8
  24. package/dist/api/base-payments.js.map +1 -1
  25. package/dist/api/nvm-api.d.ts +5 -5
  26. package/dist/api/observability-api/types.d.ts +34 -6
  27. package/dist/api/observability-api/types.d.ts.map +1 -1
  28. package/dist/api/observability-api/types.js.map +1 -1
  29. package/dist/api/plans-api.d.ts +15 -12
  30. package/dist/api/plans-api.d.ts.map +1 -1
  31. package/dist/api/plans-api.js +17 -14
  32. package/dist/api/plans-api.js.map +1 -1
  33. package/dist/api/query-api.d.ts +1 -1
  34. package/dist/common/types.d.ts +175 -18
  35. package/dist/common/types.d.ts.map +1 -1
  36. package/dist/common/types.js.map +1 -1
  37. package/dist/index.d.ts +2 -1
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +1 -0
  40. package/dist/index.js.map +1 -1
  41. package/dist/mcp/core/paywall.d.ts.map +1 -1
  42. package/dist/mcp/core/paywall.js +69 -8
  43. package/dist/mcp/core/paywall.js.map +1 -1
  44. package/dist/mcp/http/index.d.ts +1 -1
  45. package/dist/mcp/http/index.d.ts.map +1 -1
  46. package/dist/mcp/http/index.js +1 -1
  47. package/dist/mcp/http/index.js.map +1 -1
  48. package/dist/mcp/http/oauth-metadata.d.ts +32 -0
  49. package/dist/mcp/http/oauth-metadata.d.ts.map +1 -1
  50. package/dist/mcp/http/oauth-metadata.js +329 -34
  51. package/dist/mcp/http/oauth-metadata.js.map +1 -1
  52. package/dist/mcp/index.d.ts +4 -4
  53. package/dist/mcp/index.d.ts.map +1 -1
  54. package/dist/mcp/index.js +5 -5
  55. package/dist/mcp/index.js.map +1 -1
  56. package/dist/mcp/types/http.types.d.ts +38 -3
  57. package/dist/mcp/types/http.types.d.ts.map +1 -1
  58. package/dist/mcp/types/http.types.js.map +1 -1
  59. package/dist/mcp/types/paywall.types.d.ts +19 -3
  60. package/dist/mcp/types/paywall.types.d.ts.map +1 -1
  61. package/dist/mcp/types/paywall.types.js.map +1 -1
  62. package/dist/mpp/fetch.d.ts +8 -3
  63. package/dist/mpp/fetch.d.ts.map +1 -1
  64. package/dist/mpp/fetch.js +6 -0
  65. package/dist/mpp/fetch.js.map +1 -1
  66. package/dist/mpp/mpp-api.d.ts +11 -5
  67. package/dist/mpp/mpp-api.d.ts.map +1 -1
  68. package/dist/mpp/mpp-api.js +10 -3
  69. package/dist/mpp/mpp-api.js.map +1 -1
  70. package/dist/payments.d.ts.map +1 -1
  71. package/dist/x402/delegation-api.d.ts +5 -17
  72. package/dist/x402/delegation-api.d.ts.map +1 -1
  73. package/dist/x402/delegation-api.js +2 -2
  74. package/dist/x402/delegation-api.js.map +1 -1
  75. package/dist/x402/express/middleware.d.ts.map +1 -1
  76. package/dist/x402/express/middleware.js +98 -1
  77. package/dist/x402/express/middleware.js.map +1 -1
  78. package/dist/x402/facilitator-api.d.ts +90 -7
  79. package/dist/x402/facilitator-api.d.ts.map +1 -1
  80. package/dist/x402/facilitator-api.js +64 -3
  81. package/dist/x402/facilitator-api.js.map +1 -1
  82. package/dist/x402/index.d.ts +3 -2
  83. package/dist/x402/index.d.ts.map +1 -1
  84. package/dist/x402/index.js +1 -0
  85. package/dist/x402/index.js.map +1 -1
  86. package/dist/x402/token-request.d.ts +8 -0
  87. package/dist/x402/token-request.d.ts.map +1 -1
  88. package/dist/x402/token-request.js +101 -1
  89. package/dist/x402/token-request.js.map +1 -1
  90. package/dist/x402/token-version.d.ts +97 -0
  91. package/dist/x402/token-version.d.ts.map +1 -0
  92. package/dist/x402/token-version.js +127 -0
  93. package/dist/x402/token-version.js.map +1 -0
  94. package/dist/x402/token.d.ts +33 -2
  95. package/dist/x402/token.d.ts.map +1 -1
  96. package/dist/x402/token.js +47 -2
  97. package/dist/x402/token.js.map +1 -1
  98. package/package.json +22 -13
package/dist/mcp/index.js CHANGED
@@ -8,7 +8,7 @@ import { ERROR_CODES, createRpcError } from './utils/errors.js';
8
8
  // Re-export utilities
9
9
  export { buildExtraFromHttpHeaders, buildExtraFromHttpRequest } from './utils/extra.js';
10
10
  // Re-export HTTP module components for advanced usage
11
- export { getOAuthUrls, buildProtectedResourceMetadata, buildMcpProtectedResourceMetadata, buildAuthorizationServerMetadata, buildOidcConfiguration, buildServerInfoResponse, createOAuthRouter, createCorsMiddleware, createJsonMiddleware, createRequireAuthMiddleware, createHttpLoggingMiddleware, startManagedServer, createMcpApp, ClientRegistrationError, } from './http/index.js';
11
+ export { getOAuthUrls, resolveOAuthTier, OAUTH_TIER_PARAM, OAUTH_TIERS, buildProtectedResourceMetadata, buildMcpProtectedResourceMetadata, buildAuthorizationServerMetadata, buildOidcConfiguration, buildServerInfoResponse, createOAuthRouter, createCorsMiddleware, createJsonMiddleware, createRequireAuthMiddleware, createHttpLoggingMiddleware, startManagedServer, createMcpApp, ClientRegistrationError, } from './http/index.js';
12
12
  /**
13
13
  * Build MCP integration with modular architecture.
14
14
  * This function creates the complete MCP API surface including
@@ -35,7 +35,7 @@ export function buildMcpIntegration(paymentsService) {
35
35
  * @example
36
36
  * ```typescript
37
37
  * payments.mcp.configure({
38
- * planId: 'plan_123', // required
38
+ * planId: 'plan_123', // optional — omit it if every tool sets its own
39
39
  * serverName: 'my-mcp-server',
40
40
  * agentId: 'agent_123', // optional
41
41
  * baseUrl: 'http://localhost:5001',
@@ -139,7 +139,7 @@ export function buildMcpIntegration(paymentsService) {
139
139
  * ```typescript
140
140
  * const router = payments.mcp.createRouter({
141
141
  * baseUrl: 'http://localhost:5001',
142
- * planId: 'plan_123', // required
142
+ * planId: 'plan_123', // optional — falls back to configure()
143
143
  * serverName: 'my-mcp-server',
144
144
  * tools: ['hello_world']
145
145
  * })
@@ -179,7 +179,7 @@ export function buildMcpIntegration(paymentsService) {
179
179
  * ```typescript
180
180
  * const app = payments.mcp.createApp({
181
181
  * baseUrl: 'http://localhost:5001',
182
- * planId: 'plan_123', // required
182
+ * planId: 'plan_123', // optional — falls back to configure()
183
183
  * serverName: 'my-mcp-server'
184
184
  * })
185
185
  *
@@ -218,7 +218,7 @@ export function buildMcpIntegration(paymentsService) {
218
218
  * ```typescript
219
219
  * const { baseUrl, stop } = await payments.mcp.startServer({
220
220
  * port: 5001,
221
- * planId: process.env.NVM_PLAN_ID!, // required
221
+ * planId: process.env.NVM_PLAN_ID!, // optional — falls back to configure()
222
222
  * serverName: 'my-mcp-server',
223
223
  * tools: ['hello_world', 'weather']
224
224
  * })
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/mcp/index.ts"],"names":[],"mappings":"AA+DA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAA;AAC1D,OAAO,EAAE,YAAY,EAAE,kBAAkB,E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;QAET,8CAA8C;QAC9C,YAAY;QACZ,gBAAgB;QAChB,cAAc;QACd,KAAK;QACL,IAAI;KACL,CAAA;AACH,CAAC","sourcesContent":["/**\n * MCP (Model Context Protocol) integration module for Nevermined Payments.\n *\n * This module provides everything needed to build monetizable MCP servers:\n * - Paywall protection for tools, resources, and prompts\n * - OAuth 2.1 discovery and client registration endpoints\n * - Managed HTTP server or router for existing Express apps\n *\n * @example Basic usage with withPaywall\n * ```typescript\n * import { Payments } from '@nevermined-io/payments'\n *\n * const payments = Payments.getInstance({\n * nvmApiKey: process.env.NVM_API_KEY!,\n * environment: 'staging_sandbox'\n * })\n *\n * // Configure MCP integration\n * payments.mcp.configure({\n * planId: process.env.NVM_PLAN_ID!, // required\n * agentId: process.env.NVM_AGENT_ID, // optional\n * serverName: 'my-mcp-server'\n * })\n *\n * // Protect a tool handler\n * const protectedHandler = payments.mcp.withPaywall(\n * myToolHandler,\n * { kind: 'tool', name: 'my_tool', credits: 1n }\n * )\n * ```\n *\n * @example Complete server with OAuth\n * ```typescript\n * // Start a managed server with all OAuth endpoints\n * const { baseUrl, stop } = await payments.mcp.startServer({\n * port: 5001,\n * planId: process.env.NVM_PLAN_ID!, // required\n * agentId: process.env.NVM_AGENT_ID, // optional\n * serverName: 'my-mcp-server',\n * tools: ['hello_world']\n * })\n * ```\n *\n * @example Using router with existing Express app\n * ```typescript\n * import express from 'express'\n *\n * const app = express()\n *\n * // Create OAuth router\n * const router = payments.mcp.createRouter({\n * baseUrl: 'http://localhost:5001',\n * planId: 'plan_123', // required\n * agentId: 'agent_123', // optional\n * serverName: 'my-mcp-server'\n * })\n *\n * app.use(router)\n * app.listen(5001)\n * ```\n */\nimport type { Payments } from '../payments.js'\nimport type { EnvironmentName } from '../environments.js'\nimport { createOAuthRouter } from './http/oauth-router.js'\nimport { createMcpApp, startManagedServer } from './http/managed-server.js'\nimport { PaywallDecorator } from './core/paywall.js'\nimport { PaywallAuthenticator } from './core/auth.js'\nimport { CreditsContextProvider } from './core/credits-context.js'\nimport { McpServerManager, createServerManager } from './core/server-manager.js'\nimport { ERROR_CODES, createRpcError } from './utils/errors.js'\nimport type {\n McpToolConfig,\n McpResourceConfig,\n McpPromptConfig,\n McpRegistrationOptions,\n ToolHandler,\n ResourceHandler,\n PromptHandler,\n McpServerConfig,\n McpServerResult,\n} from './types/server.types.js'\nimport type {\n PaywallOptions,\n ToolOptions,\n ResourceOptions,\n PromptOptions,\n PaywallContext,\n McpConfig,\n} from './types/paywall.types.js'\nimport type { HttpServerResult } from './types/http.types.js'\n\n// Re-export types\nexport type {\n CreditsContext,\n CreditsOption,\n PaywallOptions,\n McpConfig,\n PaywallContext,\n AuthResult,\n} from './types/paywall.types.js'\n\nexport type {\n OAuthUrls,\n OAuthConfig,\n HttpRouterConfig,\n HttpServerConfig,\n HttpServerResult,\n ProtectedResourceMetadata,\n McpProtectedResourceMetadata,\n AuthorizationServerMetadata,\n OidcConfiguration,\n ClientRegistrationRequest,\n ClientRegistrationResponse,\n ServerInfoResponse,\n} from './types/http.types.js'\n\n// Re-export utilities\nexport { buildExtraFromHttpHeaders, buildExtraFromHttpRequest } from './utils/extra.js'\n\n// Re-export simplified API types\nexport type {\n McpToolConfig,\n McpResourceConfig,\n McpPromptConfig,\n McpRegistrationOptions,\n ToolHandler,\n ResourceHandler,\n PromptHandler,\n McpServerConfig,\n McpServerResult,\n ServerInfo,\n ToolContext,\n ResourceContext,\n PromptContext,\n} from './types/server.types.js'\n\n// Re-export HTTP module components for advanced usage\nexport {\n getOAuthUrls,\n buildProtectedResourceMetadata,\n buildMcpProtectedResourceMetadata,\n buildAuthorizationServerMetadata,\n buildOidcConfiguration,\n buildServerInfoResponse,\n createOAuthRouter,\n createCorsMiddleware,\n createJsonMiddleware,\n createRequireAuthMiddleware,\n createHttpLoggingMiddleware,\n startManagedServer,\n createMcpApp,\n ClientRegistrationError,\n} from './http/index.js'\n\n/**\n * Extended MCP configuration including HTTP server options.\n */\nexport interface ExtendedMcpConfig extends McpConfig {\n /** Base URL for the server (required for HTTP features) */\n baseUrl?: string\n /** Nevermined environment */\n environment?: EnvironmentName\n /** Tools exposed by this server */\n tools?: string[]\n /** Custom OAuth scopes */\n scopes?: string[]\n}\n\n/**\n * Options for creating the OAuth router.\n */\nexport interface CreateRouterOptions {\n /** Base URL of the MCP server */\n baseUrl: string\n /** Payment plan ID — configures the paywall plan for this server (falls back to configure()) */\n planId?: string\n /** Agent ID (optional; OAuth client_id / informational only) */\n agentId?: string\n /** Server name */\n serverName?: string\n /** Tools exposed by this server */\n tools?: string[]\n /** Enable OAuth discovery endpoints */\n enableOAuthDiscovery?: boolean\n /** Enable client registration */\n enableClientRegistration?: boolean\n /** Enable health check */\n enableHealthCheck?: boolean\n /** Enable server info */\n enableServerInfo?: boolean\n /** Server version */\n version?: string\n /** Server description */\n description?: string\n}\n\n/**\n * Options for starting the managed server.\n */\nexport interface StartServerOptions {\n /** Port to listen on */\n port: number\n /** Host to bind to */\n host?: string\n /** Base URL (defaults to http://localhost:\\{port\\}) */\n baseUrl?: string\n /** Payment plan ID — configures the paywall plan for this server (falls back to configure()) */\n planId?: string\n /** Agent ID (optional; OAuth client_id / informational only) */\n agentId?: string\n /** Server name */\n serverName?: string\n /** Tools exposed by this server */\n tools?: string[]\n /** Enable OAuth discovery endpoints */\n enableOAuthDiscovery?: boolean\n /** Enable client registration */\n enableClientRegistration?: boolean\n /** Enable health check */\n enableHealthCheck?: boolean\n /** Enable server info */\n enableServerInfo?: boolean\n /** Server version */\n version?: string\n /** Server description */\n description?: string\n /** Callback when server starts */\n onStart?: (result: HttpServerResult) => void\n /** Logging callback */\n onLog?: (message: string, level?: 'info' | 'warn' | 'error') => void\n}\n\n/**\n * Build MCP integration with modular architecture.\n * This function creates the complete MCP API surface including\n * paywall protection, OAuth endpoints, and HTTP server management.\n *\n * @param paymentsService - The Payments instance\n * @returns MCP integration API\n */\nexport function buildMcpIntegration(paymentsService: Payments) {\n const authenticator = new PaywallAuthenticator(paymentsService)\n const creditsContext = new CreditsContextProvider()\n const paywallDecorator = new PaywallDecorator(paymentsService, authenticator, creditsContext)\n\n // Extended configuration storage\n let extendedConfig: ExtendedMcpConfig = {\n planId: '',\n serverName: 'mcp-server',\n }\n\n /**\n * Configure the MCP integration.\n * This sets up the agent ID, server name, and optional HTTP settings.\n *\n * @param options - Configuration options\n *\n * @example\n * ```typescript\n * payments.mcp.configure({\n * planId: 'plan_123', // required\n * serverName: 'my-mcp-server',\n * agentId: 'agent_123', // optional\n * baseUrl: 'http://localhost:5001',\n * environment: 'staging_sandbox',\n * tools: ['hello_world', 'weather']\n * })\n * ```\n */\n function configure(options: ExtendedMcpConfig): void {\n extendedConfig = {\n ...extendedConfig,\n ...options,\n }\n // Also configure the paywall decorator\n paywallDecorator.configure({\n planId: options.planId,\n agentId: options.agentId,\n serverName: options.serverName,\n })\n }\n\n /**\n * Wrap a handler with paywall protection.\n * The wrapped handler will validate authentication and burn credits.\n *\n * A `planId` must already be resolvable (per-tool `options.planId` or a\n * server-level one set via `configure()`/`start()`); otherwise this throws\n * at registration time. So register paywalled handlers *after* the plan is\n * configured — e.g. `configure({ planId })` (or `start({ planId })`, which\n * configures first) before `withPaywall()`/`attach`.\n */\n function withPaywall<TArgs = any>(\n handler: (args: TArgs, extra?: any, context?: PaywallContext) => Promise<any> | any,\n options: ToolOptions | PromptOptions,\n ): (args: TArgs, extra?: any) => Promise<any>\n function withPaywall<TArgs = any>(\n handler: (args: TArgs, extra?: any, context?: PaywallContext) => Promise<any> | any,\n ): (args: TArgs, extra?: any) => Promise<any>\n function withPaywall(\n handler: (\n uri: URL,\n variables: Record<string, string | string[]>,\n extra?: any,\n context?: PaywallContext,\n ) => Promise<any> | any,\n options: ResourceOptions,\n ): (uri: URL, variables: Record<string, string | string[]>, extra?: any) => Promise<any>\n function withPaywall(handler: any, options?: ToolOptions | PromptOptions | ResourceOptions): any {\n const opts =\n (options as PaywallOptions | undefined) ?? ({ kind: 'tool', name: 'unnamed' } as any)\n // Fail fast at registration time: a planId must be resolvable from the\n // per-tool option or the server-level config. Otherwise a misconfiguration\n // would only surface on the first tool call.\n if (!opts.planId && !extendedConfig.planId) {\n throw createRpcError(ERROR_CODES.Misconfiguration, 'Server misconfiguration: missing planId')\n }\n return (paywallDecorator.protect as any)(handler, opts)\n }\n\n /**\n * Authenticate meta MCP operations (initialize, tools/list, etc.).\n *\n * @param extra - The extra parameter from MCP\n * @param method - The MCP method being called\n * @returns Authentication result\n */\n async function authenticateMeta(extra: any, options: { planId?: string } = {}, method: string) {\n const cfg = extendedConfig\n const agentId = cfg.agentId || undefined\n const serverName = cfg.serverName || 'mcp-server'\n return authenticator.authenticateMeta(\n extra,\n { planId: options?.planId ?? cfg.planId },\n agentId,\n serverName,\n method,\n )\n }\n\n /**\n * Attach paywall protection to an MCP server.\n * Returns a registrar with protected register methods.\n *\n * @param server - The MCP server instance\n * @returns Protected registrar\n */\n function attach(server: {\n registerTool: (name: string, config: any, handler: any) => void\n registerResource: (name: string, template: any, config: any, handler: any) => void\n registerPrompt: (name: string, config: any, handler: any) => void\n }) {\n return {\n registerTool<TArgs = any>(\n name: string,\n config: any,\n handler: (args: TArgs, extra?: any, context?: PaywallContext) => Promise<any> | any,\n options?: Omit<ToolOptions, 'kind' | 'name'>,\n ) {\n const protectedHandler = withPaywall(handler, { kind: 'tool', name, ...(options || {}) })\n server.registerTool(name, config, protectedHandler)\n },\n registerResource(\n name: string,\n template: any,\n config: any,\n handler: (\n uri: URL,\n variables: Record<string, string | string[]>,\n extra?: any,\n context?: PaywallContext,\n ) => Promise<any> | any,\n options?: Omit<ResourceOptions, 'kind' | 'name'>,\n ) {\n const protectedHandler = withPaywall(handler, {\n kind: 'resource',\n name,\n ...(options || {}),\n })\n server.registerResource(name, template, config, protectedHandler)\n },\n registerPrompt<TArgs = any>(\n name: string,\n config: any,\n handler: (args: TArgs, extra?: any, context?: PaywallContext) => Promise<any> | any,\n options?: Omit<PromptOptions, 'kind' | 'name'>,\n ) {\n const protectedHandler = withPaywall(handler, { kind: 'prompt', name, ...(options || {}) })\n server.registerPrompt(name, config, protectedHandler)\n },\n }\n }\n\n /**\n * Resolve the effective agentId/serverName/environment for an OAuth transport\n * from per-call options layered over the server-level config, and configure\n * the paywall so tools protected via withPaywall settle on the resolved plan\n * (per-call option wins over a prior configure()). Shared by\n * createRouter/createApp/startServer.\n *\n * agentId is optional under the plan-centric model (informational/OAuth\n * client_id only); the OAuth router omits client_id when it's absent. planId\n * is the paywall's concern — the OAuth transports below do not consume it.\n */\n function resolveTransportConfig(options: {\n planId?: string\n agentId?: string\n serverName?: string\n }): { agentId?: string; serverName: string; environment: EnvironmentName } {\n const agentId = options.agentId || extendedConfig.agentId\n const serverName = options.serverName || extendedConfig.serverName || 'mcp-server'\n configure({\n planId: options.planId ?? extendedConfig.planId,\n agentId,\n serverName,\n })\n const environment: EnvironmentName =\n extendedConfig.environment || (paymentsService as any).environmentName || 'staging_sandbox'\n return { agentId, serverName, environment }\n }\n\n /**\n * Create an Express router with OAuth 2.1 endpoints.\n * Use this when you already have an Express app and want to add OAuth support.\n *\n * @param options - Router configuration\n * @returns Express Router\n *\n * @example\n * ```typescript\n * const router = payments.mcp.createRouter({\n * baseUrl: 'http://localhost:5001',\n * planId: 'plan_123', // required\n * serverName: 'my-mcp-server',\n * tools: ['hello_world']\n * })\n *\n * app.use(router)\n * ```\n */\n function createRouter(options: CreateRouterOptions) {\n const { agentId, serverName, environment } = resolveTransportConfig(options)\n\n return createOAuthRouter({\n payments: paymentsService,\n baseUrl: options.baseUrl,\n agentId,\n environment,\n serverName,\n tools: options.tools || extendedConfig.tools || [],\n scopes: extendedConfig.scopes,\n enableOAuthDiscovery: options.enableOAuthDiscovery ?? true,\n enableClientRegistration: options.enableClientRegistration ?? true,\n enableHealthCheck: options.enableHealthCheck ?? true,\n enableServerInfo: options.enableServerInfo ?? true,\n version: options.version,\n description: options.description,\n })\n }\n\n /**\n * Create an Express app pre-configured with OAuth discovery endpoints.\n * Use this when you want more control over the app before starting.\n *\n * Note: Authentication is handled by withPaywall() on each tool,\n * not by HTTP middleware.\n *\n * @param options - App configuration\n * @returns Configured Express app with OAuth endpoints\n *\n * @example\n * ```typescript\n * const app = payments.mcp.createApp({\n * baseUrl: 'http://localhost:5001',\n * planId: 'plan_123', // required\n * serverName: 'my-mcp-server'\n * })\n *\n * // Add your MCP handler - auth via withPaywall() on each tool\n * app.post('/mcp', mcpHandler)\n *\n * app.listen(5001)\n * ```\n */\n function createApp(options: Omit<CreateRouterOptions, 'agentId'> & { agentId?: string }) {\n const { agentId, serverName, environment } = resolveTransportConfig(options)\n\n return createMcpApp({\n payments: paymentsService,\n baseUrl: options.baseUrl,\n agentId,\n environment,\n serverName,\n tools: options.tools || extendedConfig.tools || [],\n scopes: extendedConfig.scopes,\n enableOAuthDiscovery: options.enableOAuthDiscovery ?? true,\n enableClientRegistration: options.enableClientRegistration ?? true,\n enableHealthCheck: options.enableHealthCheck ?? true,\n enableServerInfo: options.enableServerInfo ?? true,\n version: options.version,\n description: options.description,\n })\n }\n\n /**\n * Start a managed HTTP server with OAuth 2.1 support.\n * This creates a complete Express server with all OAuth endpoints pre-configured.\n *\n * @param options - Server configuration\n * @returns Server result with control methods\n *\n * @example\n * ```typescript\n * const { baseUrl, stop } = await payments.mcp.startServer({\n * port: 5001,\n * planId: process.env.NVM_PLAN_ID!, // required\n * serverName: 'my-mcp-server',\n * tools: ['hello_world', 'weather']\n * })\n *\n * console.log(`Server running at ${baseUrl}`)\n *\n * // Later: gracefully stop\n * await stop()\n * ```\n */\n async function startServer(options: StartServerOptions): Promise<HttpServerResult> {\n const { agentId, serverName, environment } = resolveTransportConfig(options)\n\n const baseUrl = options.baseUrl || `http://localhost:${options.port}`\n\n return startManagedServer({\n payments: paymentsService,\n port: options.port,\n host: options.host,\n baseUrl,\n agentId,\n environment,\n serverName,\n tools: options.tools || extendedConfig.tools || [],\n scopes: extendedConfig.scopes,\n enableOAuthDiscovery: options.enableOAuthDiscovery ?? true,\n enableClientRegistration: options.enableClientRegistration ?? true,\n enableHealthCheck: options.enableHealthCheck ?? true,\n enableServerInfo: options.enableServerInfo ?? true,\n version: options.version,\n description: options.description,\n onStart: options.onStart,\n onLog: options.onLog,\n })\n }\n\n /**\n * Get the current configuration.\n *\n * @returns Current MCP configuration\n */\n function getConfig(): ExtendedMcpConfig {\n return { ...extendedConfig }\n }\n\n // =============================================================================\n // SIMPLIFIED API - High-level API that hides McpServer, Transport, and Express\n // =============================================================================\n\n // Server manager for simplified API\n let serverManager: McpServerManager | null = null\n\n /**\n * Get or create the server manager.\n */\n function getServerManager(): McpServerManager {\n if (!serverManager) {\n serverManager = createServerManager(paymentsService)\n }\n return serverManager\n }\n\n /**\n * Register a tool with the simplified API.\n * Must be called before start().\n *\n * @param name - Tool name\n * @param config - Tool configuration\n * @param handler - Tool handler function\n * @param options - Registration options (credits, etc.)\n *\n * @example\n * ```typescript\n * payments.mcp.registerTool(\n * 'hello_world',\n * {\n * description: 'Returns a hello world message',\n * inputSchema: { name: { type: 'string' } }\n * },\n * async (args: { name: string }, context?: ToolContext) => ({\n * content: [{ type: 'text', text: `Hello, ${args.name}!` }]\n * }),\n * { credits: 1, onRedeemError: 'ignore' }\n * )\n * ```\n */\n function registerTool<Args = any>(\n name: string,\n config: McpToolConfig,\n handler: ToolHandler<Args>,\n options?: McpRegistrationOptions,\n ): void {\n getServerManager().registerTool(name, config, handler, options)\n }\n\n /**\n * Register a resource with the simplified API.\n * Must be called before start().\n *\n * @param name - Resource name\n * @param uriOrTemplate - Resource URI (string) or template\n * @param config - Resource metadata configuration\n * @param handler - Resource handler function\n * @param options - Registration options (credits, etc.)\n */\n function registerResource(\n name: string,\n uriOrTemplate: string,\n config: McpResourceConfig,\n handler: ResourceHandler,\n options?: McpRegistrationOptions,\n ): void {\n getServerManager().registerResource(name, uriOrTemplate, config, handler, options)\n }\n\n /**\n * Register a prompt with the simplified API.\n * Must be called before start().\n * Matches the signature of MCP SDK registerPrompt.\n *\n * @param name - Prompt name\n * @param config - Prompt configuration\n * @param handler - Prompt handler function\n * @param options - Registration options (credits, etc.)\n */\n function registerPrompt<Args = any>(\n name: string,\n config: McpPromptConfig,\n handler: PromptHandler<Args>,\n options?: McpRegistrationOptions,\n ): void {\n getServerManager().registerPrompt(name, config, handler, options)\n }\n\n /**\n * Start the MCP server with the simplified API.\n * This creates and starts everything: McpServer, Express, OAuth endpoints, etc.\n *\n * @param config - Server configuration\n * @returns Server result with stop() method\n *\n * @example\n * ```typescript\n * // Register tools first\n * payments.mcp.registerTool('hello', { description: '...' }, handler)\n *\n * // Then start the server\n * const { info, stop } = await payments.mcp.start({\n * port: 5001,\n * planId: 'plan_123', // required\n * agentId: 'did:nv:...', // optional\n * serverName: 'my-mcp-server'\n * })\n *\n * console.log(`Server running at ${info.baseUrl}`)\n *\n * // Later: stop gracefully\n * await stop()\n * ```\n */\n async function start(config: McpServerConfig): Promise<McpServerResult> {\n return getServerManager().start(config)\n }\n\n /**\n * Stop the MCP server.\n * This is a convenience method - you can also use the stop() from start()'s result.\n */\n async function stop(): Promise<void> {\n if (serverManager) {\n await serverManager.stop()\n }\n }\n\n return {\n // Core paywall functionality (advanced API)\n configure,\n withPaywall,\n attach,\n authenticateMeta,\n\n // HTTP/OAuth functionality (advanced API)\n createRouter,\n createApp,\n startServer,\n\n // Utilities\n getConfig,\n\n // Simplified API (recommended for most users)\n registerTool,\n registerResource,\n registerPrompt,\n start,\n stop,\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/mcp/index.ts"],"names":[],"mappings":"AA+DA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAA;AAC1D,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAA;AACpD,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAA;AACrD,OAAO,EAAE,sBAAsB,EAAE,MAA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) integration module for Nevermined Payments.\n *\n * This module provides everything needed to build monetizable MCP servers:\n * - Paywall protection for tools, resources, and prompts\n * - OAuth 2.1 discovery and client registration endpoints\n * - Managed HTTP server or router for existing Express apps\n *\n * @example Basic usage with withPaywall\n * ```typescript\n * import { Payments } from '@nevermined-io/payments'\n *\n * const payments = Payments.getInstance({\n * nvmApiKey: process.env.NVM_API_KEY!,\n * environment: 'staging_sandbox'\n * })\n *\n * // Configure MCP integration\n * payments.mcp.configure({\n * planId: process.env.NVM_PLAN_ID!, // optional — omit it if every tool sets its own\n * agentId: process.env.NVM_AGENT_ID, // optional\n * serverName: 'my-mcp-server'\n * })\n *\n * // Protect a tool handler\n * const protectedHandler = payments.mcp.withPaywall(\n * myToolHandler,\n * { kind: 'tool', name: 'my_tool', credits: 1n }\n * )\n * ```\n *\n * @example Complete server with OAuth\n * ```typescript\n * // Start a managed server with all OAuth endpoints\n * const { baseUrl, stop } = await payments.mcp.startServer({\n * port: 5001,\n * planId: process.env.NVM_PLAN_ID!, // optional — falls back to configure()\n * agentId: process.env.NVM_AGENT_ID, // optional\n * serverName: 'my-mcp-server',\n * tools: ['hello_world']\n * })\n * ```\n *\n * @example Using router with existing Express app\n * ```typescript\n * import express from 'express'\n *\n * const app = express()\n *\n * // Create OAuth router\n * const router = payments.mcp.createRouter({\n * baseUrl: 'http://localhost:5001',\n * planId: 'plan_123', // optional — falls back to configure()\n * agentId: 'agent_123', // optional\n * serverName: 'my-mcp-server'\n * })\n *\n * app.use(router)\n * app.listen(5001)\n * ```\n */\nimport type { Payments } from '../payments.js'\nimport type { EnvironmentName } from '../environments.js'\nimport { createOAuthRouter } from './http/oauth-router.js'\nimport { createMcpApp, startManagedServer } from './http/managed-server.js'\nimport { PaywallDecorator } from './core/paywall.js'\nimport { PaywallAuthenticator } from './core/auth.js'\nimport { CreditsContextProvider } from './core/credits-context.js'\nimport { McpServerManager, createServerManager } from './core/server-manager.js'\nimport { ERROR_CODES, createRpcError } from './utils/errors.js'\nimport type {\n McpToolConfig,\n McpResourceConfig,\n McpPromptConfig,\n McpRegistrationOptions,\n ToolHandler,\n ResourceHandler,\n PromptHandler,\n McpServerConfig,\n McpServerResult,\n} from './types/server.types.js'\nimport type {\n PaywallOptions,\n ToolOptions,\n ResourceOptions,\n PromptOptions,\n PaywallContext,\n McpConfig,\n} from './types/paywall.types.js'\nimport type { HttpServerResult } from './types/http.types.js'\n\n// Re-export types\nexport type {\n CreditsContext,\n CreditsOption,\n PaywallOptions,\n McpConfig,\n PaywallContext,\n AuthResult,\n} from './types/paywall.types.js'\n\nexport type {\n OAuthUrls,\n OAuthConfig,\n HttpRouterConfig,\n HttpServerConfig,\n HttpServerResult,\n ProtectedResourceMetadata,\n McpProtectedResourceMetadata,\n AuthorizationServerMetadata,\n OidcConfiguration,\n ClientRegistrationRequest,\n ClientRegistrationResponse,\n ServerInfoResponse,\n} from './types/http.types.js'\n\n// Re-export utilities\nexport { buildExtraFromHttpHeaders, buildExtraFromHttpRequest } from './utils/extra.js'\n\n// Re-export simplified API types\nexport type {\n McpToolConfig,\n McpResourceConfig,\n McpPromptConfig,\n McpRegistrationOptions,\n ToolHandler,\n ResourceHandler,\n PromptHandler,\n McpServerConfig,\n McpServerResult,\n ServerInfo,\n ToolContext,\n ResourceContext,\n PromptContext,\n} from './types/server.types.js'\n\n// Re-export HTTP module components for advanced usage\nexport {\n getOAuthUrls,\n resolveOAuthTier,\n OAUTH_TIER_PARAM,\n OAUTH_TIERS,\n type OAuthTier,\n buildProtectedResourceMetadata,\n buildMcpProtectedResourceMetadata,\n buildAuthorizationServerMetadata,\n buildOidcConfiguration,\n buildServerInfoResponse,\n createOAuthRouter,\n createCorsMiddleware,\n createJsonMiddleware,\n createRequireAuthMiddleware,\n createHttpLoggingMiddleware,\n startManagedServer,\n createMcpApp,\n ClientRegistrationError,\n} from './http/index.js'\n\n/**\n * Extended MCP configuration including HTTP server options.\n */\nexport interface ExtendedMcpConfig extends McpConfig {\n /** Base URL for the server (required for HTTP features) */\n baseUrl?: string\n /** Nevermined environment */\n environment?: EnvironmentName\n /** Tools exposed by this server */\n tools?: string[]\n /** Custom OAuth scopes */\n scopes?: string[]\n}\n\n/**\n * Options for creating the OAuth router.\n */\nexport interface CreateRouterOptions {\n /** Base URL of the MCP server */\n baseUrl: string\n /** Payment plan ID — configures the paywall plan for this server (falls back to configure()) */\n planId?: string\n /** Agent ID (optional; OAuth client_id / informational only) */\n agentId?: string\n /** Server name */\n serverName?: string\n /** Tools exposed by this server */\n tools?: string[]\n /** Enable OAuth discovery endpoints */\n enableOAuthDiscovery?: boolean\n /** Enable client registration */\n enableClientRegistration?: boolean\n /** Enable health check */\n enableHealthCheck?: boolean\n /** Enable server info */\n enableServerInfo?: boolean\n /** Server version */\n version?: string\n /** Server description */\n description?: string\n}\n\n/**\n * Options for starting the managed server.\n */\nexport interface StartServerOptions {\n /** Port to listen on */\n port: number\n /** Host to bind to */\n host?: string\n /** Base URL (defaults to http://localhost:\\{port\\}) */\n baseUrl?: string\n /** Payment plan ID — configures the paywall plan for this server (falls back to configure()) */\n planId?: string\n /** Agent ID (optional; OAuth client_id / informational only) */\n agentId?: string\n /** Server name */\n serverName?: string\n /** Tools exposed by this server */\n tools?: string[]\n /** Enable OAuth discovery endpoints */\n enableOAuthDiscovery?: boolean\n /** Enable client registration */\n enableClientRegistration?: boolean\n /** Enable health check */\n enableHealthCheck?: boolean\n /** Enable server info */\n enableServerInfo?: boolean\n /** Server version */\n version?: string\n /** Server description */\n description?: string\n /** Callback when server starts */\n onStart?: (result: HttpServerResult) => void\n /** Logging callback */\n onLog?: (message: string, level?: 'info' | 'warn' | 'error') => void\n}\n\n/**\n * Build MCP integration with modular architecture.\n * This function creates the complete MCP API surface including\n * paywall protection, OAuth endpoints, and HTTP server management.\n *\n * @param paymentsService - The Payments instance\n * @returns MCP integration API\n */\nexport function buildMcpIntegration(paymentsService: Payments) {\n const authenticator = new PaywallAuthenticator(paymentsService)\n const creditsContext = new CreditsContextProvider()\n const paywallDecorator = new PaywallDecorator(paymentsService, authenticator, creditsContext)\n\n // Extended configuration storage\n let extendedConfig: ExtendedMcpConfig = {\n planId: '',\n serverName: 'mcp-server',\n }\n\n /**\n * Configure the MCP integration.\n * This sets up the agent ID, server name, and optional HTTP settings.\n *\n * @param options - Configuration options\n *\n * @example\n * ```typescript\n * payments.mcp.configure({\n * planId: 'plan_123', // optional — omit it if every tool sets its own\n * serverName: 'my-mcp-server',\n * agentId: 'agent_123', // optional\n * baseUrl: 'http://localhost:5001',\n * environment: 'staging_sandbox',\n * tools: ['hello_world', 'weather']\n * })\n * ```\n */\n function configure(options: ExtendedMcpConfig): void {\n extendedConfig = {\n ...extendedConfig,\n ...options,\n }\n // Also configure the paywall decorator\n paywallDecorator.configure({\n planId: options.planId,\n agentId: options.agentId,\n serverName: options.serverName,\n })\n }\n\n /**\n * Wrap a handler with paywall protection.\n * The wrapped handler will validate authentication and burn credits.\n *\n * A `planId` must already be resolvable (per-tool `options.planId` or a\n * server-level one set via `configure()`/`start()`); otherwise this throws\n * at registration time. So register paywalled handlers *after* the plan is\n * configured — e.g. `configure({ planId })` (or `start({ planId })`, which\n * configures first) before `withPaywall()`/`attach`.\n */\n function withPaywall<TArgs = any>(\n handler: (args: TArgs, extra?: any, context?: PaywallContext) => Promise<any> | any,\n options: ToolOptions | PromptOptions,\n ): (args: TArgs, extra?: any) => Promise<any>\n function withPaywall<TArgs = any>(\n handler: (args: TArgs, extra?: any, context?: PaywallContext) => Promise<any> | any,\n ): (args: TArgs, extra?: any) => Promise<any>\n function withPaywall(\n handler: (\n uri: URL,\n variables: Record<string, string | string[]>,\n extra?: any,\n context?: PaywallContext,\n ) => Promise<any> | any,\n options: ResourceOptions,\n ): (uri: URL, variables: Record<string, string | string[]>, extra?: any) => Promise<any>\n function withPaywall(handler: any, options?: ToolOptions | PromptOptions | ResourceOptions): any {\n const opts =\n (options as PaywallOptions | undefined) ?? ({ kind: 'tool', name: 'unnamed' } as any)\n // Fail fast at registration time: a planId must be resolvable from the\n // per-tool option or the server-level config. Otherwise a misconfiguration\n // would only surface on the first tool call.\n if (!opts.planId && !extendedConfig.planId) {\n throw createRpcError(ERROR_CODES.Misconfiguration, 'Server misconfiguration: missing planId')\n }\n return (paywallDecorator.protect as any)(handler, opts)\n }\n\n /**\n * Authenticate meta MCP operations (initialize, tools/list, etc.).\n *\n * @param extra - The extra parameter from MCP\n * @param method - The MCP method being called\n * @returns Authentication result\n */\n async function authenticateMeta(extra: any, options: { planId?: string } = {}, method: string) {\n const cfg = extendedConfig\n const agentId = cfg.agentId || undefined\n const serverName = cfg.serverName || 'mcp-server'\n return authenticator.authenticateMeta(\n extra,\n { planId: options?.planId ?? cfg.planId },\n agentId,\n serverName,\n method,\n )\n }\n\n /**\n * Attach paywall protection to an MCP server.\n * Returns a registrar with protected register methods.\n *\n * @param server - The MCP server instance\n * @returns Protected registrar\n */\n function attach(server: {\n registerTool: (name: string, config: any, handler: any) => void\n registerResource: (name: string, template: any, config: any, handler: any) => void\n registerPrompt: (name: string, config: any, handler: any) => void\n }) {\n return {\n registerTool<TArgs = any>(\n name: string,\n config: any,\n handler: (args: TArgs, extra?: any, context?: PaywallContext) => Promise<any> | any,\n options?: Omit<ToolOptions, 'kind' | 'name'>,\n ) {\n const protectedHandler = withPaywall(handler, { kind: 'tool', name, ...(options || {}) })\n server.registerTool(name, config, protectedHandler)\n },\n registerResource(\n name: string,\n template: any,\n config: any,\n handler: (\n uri: URL,\n variables: Record<string, string | string[]>,\n extra?: any,\n context?: PaywallContext,\n ) => Promise<any> | any,\n options?: Omit<ResourceOptions, 'kind' | 'name'>,\n ) {\n const protectedHandler = withPaywall(handler, {\n kind: 'resource',\n name,\n ...(options || {}),\n })\n server.registerResource(name, template, config, protectedHandler)\n },\n registerPrompt<TArgs = any>(\n name: string,\n config: any,\n handler: (args: TArgs, extra?: any, context?: PaywallContext) => Promise<any> | any,\n options?: Omit<PromptOptions, 'kind' | 'name'>,\n ) {\n const protectedHandler = withPaywall(handler, { kind: 'prompt', name, ...(options || {}) })\n server.registerPrompt(name, config, protectedHandler)\n },\n }\n }\n\n /**\n * Resolve the effective agentId/serverName/environment for an OAuth transport\n * from per-call options layered over the server-level config, and configure\n * the paywall so tools protected via withPaywall settle on the resolved plan\n * (per-call option wins over a prior configure()). Shared by\n * createRouter/createApp/startServer.\n *\n * agentId is optional under the plan-centric model (informational/OAuth\n * client_id only); the OAuth router omits client_id when it's absent. planId\n * is the paywall's concern — the OAuth transports below do not consume it.\n */\n function resolveTransportConfig(options: {\n planId?: string\n agentId?: string\n serverName?: string\n }): { agentId?: string; serverName: string; environment: EnvironmentName } {\n const agentId = options.agentId || extendedConfig.agentId\n const serverName = options.serverName || extendedConfig.serverName || 'mcp-server'\n configure({\n planId: options.planId ?? extendedConfig.planId,\n agentId,\n serverName,\n })\n const environment: EnvironmentName =\n extendedConfig.environment || (paymentsService as any).environmentName || 'staging_sandbox'\n return { agentId, serverName, environment }\n }\n\n /**\n * Create an Express router with OAuth 2.1 endpoints.\n * Use this when you already have an Express app and want to add OAuth support.\n *\n * @param options - Router configuration\n * @returns Express Router\n *\n * @example\n * ```typescript\n * const router = payments.mcp.createRouter({\n * baseUrl: 'http://localhost:5001',\n * planId: 'plan_123', // optional — falls back to configure()\n * serverName: 'my-mcp-server',\n * tools: ['hello_world']\n * })\n *\n * app.use(router)\n * ```\n */\n function createRouter(options: CreateRouterOptions) {\n const { agentId, serverName, environment } = resolveTransportConfig(options)\n\n return createOAuthRouter({\n payments: paymentsService,\n baseUrl: options.baseUrl,\n agentId,\n environment,\n serverName,\n tools: options.tools || extendedConfig.tools || [],\n scopes: extendedConfig.scopes,\n enableOAuthDiscovery: options.enableOAuthDiscovery ?? true,\n enableClientRegistration: options.enableClientRegistration ?? true,\n enableHealthCheck: options.enableHealthCheck ?? true,\n enableServerInfo: options.enableServerInfo ?? true,\n version: options.version,\n description: options.description,\n })\n }\n\n /**\n * Create an Express app pre-configured with OAuth discovery endpoints.\n * Use this when you want more control over the app before starting.\n *\n * Note: Authentication is handled by withPaywall() on each tool,\n * not by HTTP middleware.\n *\n * @param options - App configuration\n * @returns Configured Express app with OAuth endpoints\n *\n * @example\n * ```typescript\n * const app = payments.mcp.createApp({\n * baseUrl: 'http://localhost:5001',\n * planId: 'plan_123', // optional — falls back to configure()\n * serverName: 'my-mcp-server'\n * })\n *\n * // Add your MCP handler - auth via withPaywall() on each tool\n * app.post('/mcp', mcpHandler)\n *\n * app.listen(5001)\n * ```\n */\n function createApp(options: Omit<CreateRouterOptions, 'agentId'> & { agentId?: string }) {\n const { agentId, serverName, environment } = resolveTransportConfig(options)\n\n return createMcpApp({\n payments: paymentsService,\n baseUrl: options.baseUrl,\n agentId,\n environment,\n serverName,\n tools: options.tools || extendedConfig.tools || [],\n scopes: extendedConfig.scopes,\n enableOAuthDiscovery: options.enableOAuthDiscovery ?? true,\n enableClientRegistration: options.enableClientRegistration ?? true,\n enableHealthCheck: options.enableHealthCheck ?? true,\n enableServerInfo: options.enableServerInfo ?? true,\n version: options.version,\n description: options.description,\n })\n }\n\n /**\n * Start a managed HTTP server with OAuth 2.1 support.\n * This creates a complete Express server with all OAuth endpoints pre-configured.\n *\n * @param options - Server configuration\n * @returns Server result with control methods\n *\n * @example\n * ```typescript\n * const { baseUrl, stop } = await payments.mcp.startServer({\n * port: 5001,\n * planId: process.env.NVM_PLAN_ID!, // optional — falls back to configure()\n * serverName: 'my-mcp-server',\n * tools: ['hello_world', 'weather']\n * })\n *\n * console.log(`Server running at ${baseUrl}`)\n *\n * // Later: gracefully stop\n * await stop()\n * ```\n */\n async function startServer(options: StartServerOptions): Promise<HttpServerResult> {\n const { agentId, serverName, environment } = resolveTransportConfig(options)\n\n const baseUrl = options.baseUrl || `http://localhost:${options.port}`\n\n return startManagedServer({\n payments: paymentsService,\n port: options.port,\n host: options.host,\n baseUrl,\n agentId,\n environment,\n serverName,\n tools: options.tools || extendedConfig.tools || [],\n scopes: extendedConfig.scopes,\n enableOAuthDiscovery: options.enableOAuthDiscovery ?? true,\n enableClientRegistration: options.enableClientRegistration ?? true,\n enableHealthCheck: options.enableHealthCheck ?? true,\n enableServerInfo: options.enableServerInfo ?? true,\n version: options.version,\n description: options.description,\n onStart: options.onStart,\n onLog: options.onLog,\n })\n }\n\n /**\n * Get the current configuration.\n *\n * @returns Current MCP configuration\n */\n function getConfig(): ExtendedMcpConfig {\n return { ...extendedConfig }\n }\n\n // =============================================================================\n // SIMPLIFIED API - High-level API that hides McpServer, Transport, and Express\n // =============================================================================\n\n // Server manager for simplified API\n let serverManager: McpServerManager | null = null\n\n /**\n * Get or create the server manager.\n */\n function getServerManager(): McpServerManager {\n if (!serverManager) {\n serverManager = createServerManager(paymentsService)\n }\n return serverManager\n }\n\n /**\n * Register a tool with the simplified API.\n * Must be called before start().\n *\n * @param name - Tool name\n * @param config - Tool configuration\n * @param handler - Tool handler function\n * @param options - Registration options (credits, etc.)\n *\n * @example\n * ```typescript\n * payments.mcp.registerTool(\n * 'hello_world',\n * {\n * description: 'Returns a hello world message',\n * inputSchema: { name: { type: 'string' } }\n * },\n * async (args: { name: string }, context?: ToolContext) => ({\n * content: [{ type: 'text', text: `Hello, ${args.name}!` }]\n * }),\n * { credits: 1, onRedeemError: 'ignore' }\n * )\n * ```\n */\n function registerTool<Args = any>(\n name: string,\n config: McpToolConfig,\n handler: ToolHandler<Args>,\n options?: McpRegistrationOptions,\n ): void {\n getServerManager().registerTool(name, config, handler, options)\n }\n\n /**\n * Register a resource with the simplified API.\n * Must be called before start().\n *\n * @param name - Resource name\n * @param uriOrTemplate - Resource URI (string) or template\n * @param config - Resource metadata configuration\n * @param handler - Resource handler function\n * @param options - Registration options (credits, etc.)\n */\n function registerResource(\n name: string,\n uriOrTemplate: string,\n config: McpResourceConfig,\n handler: ResourceHandler,\n options?: McpRegistrationOptions,\n ): void {\n getServerManager().registerResource(name, uriOrTemplate, config, handler, options)\n }\n\n /**\n * Register a prompt with the simplified API.\n * Must be called before start().\n * Matches the signature of MCP SDK registerPrompt.\n *\n * @param name - Prompt name\n * @param config - Prompt configuration\n * @param handler - Prompt handler function\n * @param options - Registration options (credits, etc.)\n */\n function registerPrompt<Args = any>(\n name: string,\n config: McpPromptConfig,\n handler: PromptHandler<Args>,\n options?: McpRegistrationOptions,\n ): void {\n getServerManager().registerPrompt(name, config, handler, options)\n }\n\n /**\n * Start the MCP server with the simplified API.\n * This creates and starts everything: McpServer, Express, OAuth endpoints, etc.\n *\n * @param config - Server configuration\n * @returns Server result with stop() method\n *\n * @example\n * ```typescript\n * // Register tools first\n * payments.mcp.registerTool('hello', { description: '...' }, handler)\n *\n * // Then start the server\n * const { info, stop } = await payments.mcp.start({\n * port: 5001,\n * planId: 'plan_123', // required\n * agentId: 'did:nv:...', // optional\n * serverName: 'my-mcp-server'\n * })\n *\n * console.log(`Server running at ${info.baseUrl}`)\n *\n * // Later: stop gracefully\n * await stop()\n * ```\n */\n async function start(config: McpServerConfig): Promise<McpServerResult> {\n return getServerManager().start(config)\n }\n\n /**\n * Stop the MCP server.\n * This is a convenience method - you can also use the stop() from start()'s result.\n */\n async function stop(): Promise<void> {\n if (serverManager) {\n await serverManager.stop()\n }\n }\n\n return {\n // Core paywall functionality (advanced API)\n configure,\n withPaywall,\n attach,\n authenticateMeta,\n\n // HTTP/OAuth functionality (advanced API)\n createRouter,\n createApp,\n startServer,\n\n // Utilities\n getConfig,\n\n // Simplified API (recommended for most users)\n registerTool,\n registerResource,\n registerPrompt,\n start,\n stop,\n }\n}\n"]}
@@ -8,11 +8,39 @@ import type { EnvironmentName } from '../../environments.js';
8
8
  * These URLs are used to build the OAuth discovery metadata.
9
9
  */
10
10
  export interface OAuthUrls {
11
- /** The issuer identifier (e.g., https://nevermined.app) */
11
+ /**
12
+ * The RFC 8414 issuer identifier — the CANONICAL origin of the Nevermined API this server runs
13
+ * against (e.g. `https://api.sandbox.nevermined.app`), one per tier: the value the API's own
14
+ * discovery document publishes and the web app returns as RFC 9207 `iss`. A named environment
15
+ * publishes its own canonical origin whatever `tokenUri` proxy sits in front of it; `custom`
16
+ * follows the backend it publishes, canonicalised for a Nevermined host. It was the frontend
17
+ * origin until #463 was fixed (payments#464): tier-blind, and rejected by RFC 9207 clients once
18
+ * the web app started returning `iss`. A non-empty explicit override is passed through unchanged
19
+ * and also becomes the protected-resource document's `authorization_servers` entry.
20
+ */
12
21
  issuer: string;
13
- /** OAuth authorization endpoint URL */
22
+ /**
23
+ * OAuth authorization endpoint URL — the Nevermined webapp's consent page, **tier-qualified**
24
+ * (`https://nevermined.app/oauth/authorize?network=sandbox|live`; nvm-monorepo#3430). An override
25
+ * is published verbatim: if you point it at the Nevermined webapp yourself (e.g. a `custom`
26
+ * environment behind a host the SDK cannot classify), include `?network=<tier>` in the value.
27
+ * Overriding it also withdraws the RFC 9207 `authorization_response_iss_parameter_supported`
28
+ * advertisement from the discovery documents — the SDK cannot vouch that an AS it did not choose
29
+ * returns `iss`. That is a trade, not a non-event: RFC 9207 §2.4 has a client REJECT an `iss`-less
30
+ * response from a server that advertises support, and SHOULD DISCARD a response that carries
31
+ * `iss` from one that does not — so if the override still points at the Nevermined web app, which
32
+ * returns `iss` on every response, a strict client may discard its responses (payments#466).
33
+ */
14
34
  authorizationUri: string;
15
- /** OAuth token endpoint URL */
35
+ /**
36
+ * OAuth token endpoint URL (`${backend}/oauth/token`).
37
+ *
38
+ * ⚠️ An override here is honoured only by a client that discovers against THIS server's own
39
+ * document. The protected-resource document's `authorization_servers` names the issuer (the
40
+ * canonical API origin), so an RFC 9728 client fetches the Nevermined API's own metadata and
41
+ * exchanges its code at `${API origin}/oauth/token` — around any proxy set here — and sees no
42
+ * `registration_endpoint` there (the API offers no DCR; this server does). payments#464.
43
+ */
16
44
  tokenUri: string;
17
45
  /** JSON Web Key Set endpoint URL */
18
46
  jwksUri: string;
@@ -123,6 +151,13 @@ export interface AuthorizationServerMetadata {
123
151
  scopes_supported: string[];
124
152
  token_endpoint_auth_methods_supported: string[];
125
153
  subject_types_supported: string[];
154
+ /**
155
+ * RFC 9207 §3 — present (and `true`) when every authorization response carries `iss`: the four
156
+ * named environments (the Nevermined web app returns it; nvm-monorepo#3532). Omitted — which the
157
+ * RFC defines as `false` — for `custom` and when `authorizationUri` is overridden. The wire type is
158
+ * a boolean; this SDK never publishes an explicit `false`.
159
+ */
160
+ authorization_response_iss_parameter_supported?: boolean;
126
161
  }
127
162
  /**
128
163
  * OpenID Connect Discovery Metadata.
@@ -1 +1 @@
1
- {"version":3,"file":"http.types.d.ts","sourceRoot":"","sources":["../../../src/mcp/types/http.types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AAE5D;;;GAGG;AACH,MAAM,WAAW,SAAS;IACxB,2DAA2D;IAC3D,MAAM,EAAE,MAAM,CAAA;IACd,uCAAuC;IACvC,gBAAgB,EAAE,MAAM,CAAA;IACxB,+BAA+B;IAC/B,QAAQ,EAAE,MAAM,CAAA;IAChB,oCAAoC;IACpC,OAAO,EAAE,MAAM,CAAA;IACf,2CAA2C;IAC3C,WAAW,EAAE,MAAM,CAAA;CACpB;AAED;;GAEG;AACH,eAAO,MAAM,oBAAoB,iFAOvB,CAAA;AAEV,MAAM,MAAM,UAAU,GAAG,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAA;AAE9D;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,+DAA+D;IAC/D,OAAO,EAAE,MAAM,CAAA;IACf,0EAA0E;IAC1E,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,kDAAkD;IAClD,WAAW,EAAE,eAAe,CAAA;IAC5B,yDAAyD;IACzD,SAAS,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,CAAA;IAC9B,sCAAsC;IACtC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAA;IACjB,mCAAmC;IACnC,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,gDAAgD;IAChD,KAAK,CAAC,EAAE,MAAM,EAA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AAM,oBAAoB,GAAG;IAClC,QAAQ;IACR,SAAS;IACT,SAAS;IACT,UAAU;IACV,WAAW;IACX,WAAW;CACH,CAAA","sourcesContent":["/**\n * Type definitions for MCP HTTP server and OAuth 2.1 integration.\n * These types configure the automatic OAuth endpoints and HTTP server functionality.\n */\nimport type { EnvironmentName } from '../../environments.js'\n\n/**\n * OAuth URLs configuration for Nevermined authorization server.\n * These URLs are used to build the OAuth discovery metadata.\n */\nexport interface OAuthUrls {\n /** The issuer identifier (e.g., https://nevermined.app) */\n issuer: string\n /** OAuth authorization endpoint URL */\n authorizationUri: string\n /** OAuth token endpoint URL */\n tokenUri: string\n /** JSON Web Key Set endpoint URL */\n jwksUri: string\n /** OpenID Connect userinfo endpoint URL */\n userinfoUri: string\n}\n\n/**\n * Scopes supported by the MCP OAuth integration.\n */\nexport const DEFAULT_OAUTH_SCOPES = [\n 'openid',\n 'profile',\n 'credits',\n 'mcp:read',\n 'mcp:write',\n 'mcp:tools',\n] as const\n\nexport type OAuthScope = (typeof DEFAULT_OAUTH_SCOPES)[number]\n\n/**\n * Configuration for OAuth endpoints and metadata.\n */\nexport interface OAuthConfig {\n /** Base URL of the MCP server (e.g., http://localhost:5001) */\n baseUrl: string\n /** Agent ID (client_id) for OAuth flows — optional, informational only */\n agentId?: string\n /** Nevermined environment to derive OAuth URLs */\n environment: EnvironmentName\n /** Custom OAuth URLs (overrides environment defaults) */\n oauthUrls?: Partial<OAuthUrls>\n /** Scopes supported by this server */\n scopes?: string[]\n /** Server name for MCP protocol */\n serverName?: string\n /** List of tool names exposed by this server */\n tools?: string[]\n /** List of resource names exposed by this server */\n resources?: string[]\n /** List of prompt names exposed by this server */\n prompts?: string[]\n /** MCP protocol version */\n protocolVersion?: string\n}\n\n/**\n * Configuration for the HTTP router.\n */\nexport interface HttpRouterConfig extends OAuthConfig {\n /** Enable OAuth discovery endpoints (/.well-known/*) */\n enableOAuthDiscovery?: boolean\n /** Enable dynamic client registration (/register) */\n enableClientRegistration?: boolean\n /** Enable health check endpoint (/health) */\n enableHealthCheck?: boolean\n /** Enable server info endpoint (/) */\n enableServerInfo?: boolean\n /** Custom CORS origins (default: '*') */\n corsOrigins?: string | string[]\n}\n\n/**\n * Configuration for the managed HTTP server.\n */\nexport interface HttpServerConfig extends HttpRouterConfig {\n /** Port to listen on */\n port: number\n /** Host to bind to (default: '0.0.0.0') */\n host?: string\n}\n\n/**\n * Result returned when starting the managed HTTP server.\n */\nexport interface HttpServerResult {\n /** The underlying HTTP server instance */\n server: import('http').Server\n /** The Express application instance */\n app: import('express').Application\n /** Stop the server gracefully */\n stop: () => Promise<void>\n /** The base URL of the running server */\n baseUrl: string\n /** The port the server is listening on */\n port: number\n}\n\n/**\n * OAuth Protected Resource Metadata response (RFC 9728).\n */\nexport interface ProtectedResourceMetadata {\n resource: string\n authorization_servers: string[]\n scopes_supported: string[]\n bearer_methods_supported: string[]\n resource_documentation?: string\n}\n\n/**\n * MCP-specific Protected Resource Metadata.\n */\nexport interface McpProtectedResourceMetadata extends ProtectedResourceMetadata {\n scopes_required?: string[]\n mcp_capabilities?: {\n tools?: string[]\n protocol_version?: string\n }\n}\n\n/**\n * OAuth Authorization Server Metadata response (RFC 8414).\n */\nexport interface AuthorizationServerMetadata {\n issuer: string\n authorization_endpoint: string\n token_endpoint: string\n registration_endpoint?: string\n jwks_uri: string\n response_types_supported: string[]\n grant_types_supported: string[]\n code_challenge_methods_supported: string[]\n scopes_supported: string[]\n token_endpoint_auth_methods_supported: string[]\n subject_types_supported: string[]\n}\n\n/**\n * OpenID Connect Discovery Metadata.\n */\nexport interface OidcConfiguration extends AuthorizationServerMetadata {\n userinfo_endpoint?: string\n id_token_signing_alg_values_supported?: string[]\n claims_supported?: string[]\n}\n\n/**\n * OAuth Dynamic Client Registration request (RFC 7591).\n */\nexport interface ClientRegistrationRequest {\n redirect_uris: string[]\n client_name?: string\n client_uri?: string\n logo_uri?: string\n scope?: string\n grant_types?: string[]\n response_types?: string[]\n token_endpoint_auth_method?: string\n contacts?: string[]\n}\n\n/**\n * OAuth Dynamic Client Registration response (RFC 7591).\n */\nexport interface ClientRegistrationResponse {\n client_id: string\n client_id_issued_at: number\n client_name?: string\n redirect_uris: string[]\n scope?: string\n grant_types?: string[]\n response_types?: string[]\n token_endpoint_auth_method?: string\n client_secret?: string\n client_secret_expires_at?: number\n client_uri?: string\n logo_uri?: string\n contacts?: string[]\n}\n\n/**\n * Server info response for the root endpoint.\n */\nexport interface ServerInfoResponse {\n name: string\n version: string\n description?: string\n endpoints: {\n mcp: string\n health?: string\n register?: string\n }\n oauth?: {\n authorization_server_metadata: string\n protected_resource_metadata: string\n openid_configuration: string\n authorization_endpoint: string\n token_endpoint: string\n jwks_uri: string\n registration_endpoint?: string\n client_id: string\n scopes: string[]\n }\n tools?: string[]\n resources?: string[]\n prompts?: string[]\n}\n"]}
1
+ {"version":3,"file":"http.types.js","sourceRoot":"","sources":["../../../src/mcp/types/http.types.ts"],"names":[],"mappings":"AAmDA;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,QAAQ;IACR,SAAS;IACT,SAAS;IACT,UAAU;IACV,WAAW;IACX,WAAW;CACH,CAAA","sourcesContent":["/**\n * Type definitions for MCP HTTP server and OAuth 2.1 integration.\n * These types configure the automatic OAuth endpoints and HTTP server functionality.\n */\nimport type { EnvironmentName } from '../../environments.js'\n\n/**\n * OAuth URLs configuration for Nevermined authorization server.\n * These URLs are used to build the OAuth discovery metadata.\n */\nexport interface OAuthUrls {\n /**\n * The RFC 8414 issuer identifier — the CANONICAL origin of the Nevermined API this server runs\n * against (e.g. `https://api.sandbox.nevermined.app`), one per tier: the value the API's own\n * discovery document publishes and the web app returns as RFC 9207 `iss`. A named environment\n * publishes its own canonical origin whatever `tokenUri` proxy sits in front of it; `custom`\n * follows the backend it publishes, canonicalised for a Nevermined host. It was the frontend\n * origin until #463 was fixed (payments#464): tier-blind, and rejected by RFC 9207 clients once\n * the web app started returning `iss`. A non-empty explicit override is passed through unchanged\n * and also becomes the protected-resource document's `authorization_servers` entry.\n */\n issuer: string\n /**\n * OAuth authorization endpoint URL — the Nevermined webapp's consent page, **tier-qualified**\n * (`https://nevermined.app/oauth/authorize?network=sandbox|live`; nvm-monorepo#3430). An override\n * is published verbatim: if you point it at the Nevermined webapp yourself (e.g. a `custom`\n * environment behind a host the SDK cannot classify), include `?network=<tier>` in the value.\n * Overriding it also withdraws the RFC 9207 `authorization_response_iss_parameter_supported`\n * advertisement from the discovery documents — the SDK cannot vouch that an AS it did not choose\n * returns `iss`. That is a trade, not a non-event: RFC 9207 §2.4 has a client REJECT an `iss`-less\n * response from a server that advertises support, and SHOULD DISCARD a response that carries\n * `iss` from one that does not — so if the override still points at the Nevermined web app, which\n * returns `iss` on every response, a strict client may discard its responses (payments#466).\n */\n authorizationUri: string\n /**\n * OAuth token endpoint URL (`${backend}/oauth/token`).\n *\n * ⚠️ An override here is honoured only by a client that discovers against THIS server's own\n * document. The protected-resource document's `authorization_servers` names the issuer (the\n * canonical API origin), so an RFC 9728 client fetches the Nevermined API's own metadata and\n * exchanges its code at `${API origin}/oauth/token` — around any proxy set here — and sees no\n * `registration_endpoint` there (the API offers no DCR; this server does). payments#464.\n */\n tokenUri: string\n /** JSON Web Key Set endpoint URL */\n jwksUri: string\n /** OpenID Connect userinfo endpoint URL */\n userinfoUri: string\n}\n\n/**\n * Scopes supported by the MCP OAuth integration.\n */\nexport const DEFAULT_OAUTH_SCOPES = [\n 'openid',\n 'profile',\n 'credits',\n 'mcp:read',\n 'mcp:write',\n 'mcp:tools',\n] as const\n\nexport type OAuthScope = (typeof DEFAULT_OAUTH_SCOPES)[number]\n\n/**\n * Configuration for OAuth endpoints and metadata.\n */\nexport interface OAuthConfig {\n /** Base URL of the MCP server (e.g., http://localhost:5001) */\n baseUrl: string\n /** Agent ID (client_id) for OAuth flows — optional, informational only */\n agentId?: string\n /** Nevermined environment to derive OAuth URLs */\n environment: EnvironmentName\n /** Custom OAuth URLs (overrides environment defaults) */\n oauthUrls?: Partial<OAuthUrls>\n /** Scopes supported by this server */\n scopes?: string[]\n /** Server name for MCP protocol */\n serverName?: string\n /** List of tool names exposed by this server */\n tools?: string[]\n /** List of resource names exposed by this server */\n resources?: string[]\n /** List of prompt names exposed by this server */\n prompts?: string[]\n /** MCP protocol version */\n protocolVersion?: string\n}\n\n/**\n * Configuration for the HTTP router.\n */\nexport interface HttpRouterConfig extends OAuthConfig {\n /** Enable OAuth discovery endpoints (/.well-known/*) */\n enableOAuthDiscovery?: boolean\n /** Enable dynamic client registration (/register) */\n enableClientRegistration?: boolean\n /** Enable health check endpoint (/health) */\n enableHealthCheck?: boolean\n /** Enable server info endpoint (/) */\n enableServerInfo?: boolean\n /** Custom CORS origins (default: '*') */\n corsOrigins?: string | string[]\n}\n\n/**\n * Configuration for the managed HTTP server.\n */\nexport interface HttpServerConfig extends HttpRouterConfig {\n /** Port to listen on */\n port: number\n /** Host to bind to (default: '0.0.0.0') */\n host?: string\n}\n\n/**\n * Result returned when starting the managed HTTP server.\n */\nexport interface HttpServerResult {\n /** The underlying HTTP server instance */\n server: import('http').Server\n /** The Express application instance */\n app: import('express').Application\n /** Stop the server gracefully */\n stop: () => Promise<void>\n /** The base URL of the running server */\n baseUrl: string\n /** The port the server is listening on */\n port: number\n}\n\n/**\n * OAuth Protected Resource Metadata response (RFC 9728).\n */\nexport interface ProtectedResourceMetadata {\n resource: string\n authorization_servers: string[]\n scopes_supported: string[]\n bearer_methods_supported: string[]\n resource_documentation?: string\n}\n\n/**\n * MCP-specific Protected Resource Metadata.\n */\nexport interface McpProtectedResourceMetadata extends ProtectedResourceMetadata {\n scopes_required?: string[]\n mcp_capabilities?: {\n tools?: string[]\n protocol_version?: string\n }\n}\n\n/**\n * OAuth Authorization Server Metadata response (RFC 8414).\n */\nexport interface AuthorizationServerMetadata {\n issuer: string\n authorization_endpoint: string\n token_endpoint: string\n registration_endpoint?: string\n jwks_uri: string\n response_types_supported: string[]\n grant_types_supported: string[]\n code_challenge_methods_supported: string[]\n scopes_supported: string[]\n token_endpoint_auth_methods_supported: string[]\n subject_types_supported: string[]\n /**\n * RFC 9207 §3 — present (and `true`) when every authorization response carries `iss`: the four\n * named environments (the Nevermined web app returns it; nvm-monorepo#3532). Omitted — which the\n * RFC defines as `false` — for `custom` and when `authorizationUri` is overridden. The wire type is\n * a boolean; this SDK never publishes an explicit `false`.\n */\n authorization_response_iss_parameter_supported?: boolean\n}\n\n/**\n * OpenID Connect Discovery Metadata.\n */\nexport interface OidcConfiguration extends AuthorizationServerMetadata {\n userinfo_endpoint?: string\n id_token_signing_alg_values_supported?: string[]\n claims_supported?: string[]\n}\n\n/**\n * OAuth Dynamic Client Registration request (RFC 7591).\n */\nexport interface ClientRegistrationRequest {\n redirect_uris: string[]\n client_name?: string\n client_uri?: string\n logo_uri?: string\n scope?: string\n grant_types?: string[]\n response_types?: string[]\n token_endpoint_auth_method?: string\n contacts?: string[]\n}\n\n/**\n * OAuth Dynamic Client Registration response (RFC 7591).\n */\nexport interface ClientRegistrationResponse {\n client_id: string\n client_id_issued_at: number\n client_name?: string\n redirect_uris: string[]\n scope?: string\n grant_types?: string[]\n response_types?: string[]\n token_endpoint_auth_method?: string\n client_secret?: string\n client_secret_expires_at?: number\n client_uri?: string\n logo_uri?: string\n contacts?: string[]\n}\n\n/**\n * Server info response for the root endpoint.\n */\nexport interface ServerInfoResponse {\n name: string\n version: string\n description?: string\n endpoints: {\n mcp: string\n health?: string\n register?: string\n }\n oauth?: {\n authorization_server_metadata: string\n protected_resource_metadata: string\n openid_configuration: string\n authorization_endpoint: string\n token_endpoint: string\n jwks_uri: string\n registration_endpoint?: string\n client_id: string\n scopes: string[]\n }\n tools?: string[]\n resources?: string[]\n prompts?: string[]\n}\n"]}
@@ -84,9 +84,25 @@ export interface PaywallContext {
84
84
  * MCP integration configuration
85
85
  */
86
86
  export interface McpConfig {
87
- /** Plan ID the server charges against (required). The facilitator is
88
- * plan-centric: verify/settle resolve everything from the plan + token. */
89
- planId: string;
87
+ /**
88
+ * Plan ID the server charges against. The facilitator is plan-centric:
89
+ * verify/settle resolve everything from the plan + token.
90
+ *
91
+ * Optional because a planId only has to be **resolvable by the time a handler
92
+ * runs**, and a per-tool `options.planId` satisfies that on its own:
93
+ * `PaywallDecorator` resolves `options?.planId ?? this.config.planId` and
94
+ * refuses only when both are absent (`Server misconfiguration: missing
95
+ * planId`). `withPaywall`'s own docblock has always documented that form.
96
+ *
97
+ * It was declared required anyway, which made `configure({ agentId })` a
98
+ * compile error for a server that sets its plan per tool — a configuration
99
+ * the runtime supports and the docs describe. The type was the only one of the
100
+ * three that forbade it.
101
+ *
102
+ * Set it here when one plan covers the whole server; omit it when every
103
+ * paywalled handler passes its own.
104
+ */
105
+ planId?: string;
90
106
  /** Agent ID — optional, informational/observability only. */
91
107
  agentId?: string;
92
108
  serverName?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"paywall.types.d.ts","sourceRoot":"","sources":["../../../src/mcp/types/paywall.types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAA;AAEvE;;GAEG;AACH;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,OAAO,CAAA;IACb,MAAM,EAAE,GAAG,CAAA;IACX,OAAO,EAAE;QACP,UAAU,EAAE,MAAM,CAAA;QAClB,UAAU,EAAE,MAAM,CAAA;QAClB,QAAQ,EAAE,MAAM,CAAA;KACjB,CAAA;CACF;AAED;;GAEG;AACH;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,CAAC,CAAC,GAAG,EAAE,cAAc,KAAK,MAAM,CAAC,CAAA;AAEtE;;GAEG;AACH;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAA;IACZ,OAAO,CAAC,EAAE,aAAa,CAAA;IACvB,aAAa,CAAC,EAAE,QAAQ,GAAG,WAAW,CAAA;I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Ac;IAC7B,UAAU,EAAE,UAAU,CAAA;IACtB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,iBAAiB,EAAE,OAAO,CAAA;IAC1B,YAAY,CAAC,EAAE,iBAAiB,CAAA;CACjC;AAED;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB;;;;;;;;;;;;;;;;;OAiBG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,6DAA6D;IAC7D,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB"}
@@ -1 +1 @@
1
- {"version":3,"file":"paywall.types.js","sourceRoot":"","sources":["../../../src/mcp/types/paywall.types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * Type definitions for MCP paywall functionality\n */\nimport type { Address, StartAgentRequest } from '../../common/types.js'\n\n/**\n * Context provided to dynamic credits functions\n */\n/**\n * Context provided to dynamic credits functions.\n */\nexport interface CreditsContext {\n args: unknown\n result: any\n request: {\n authHeader: string\n logicalUrl: string\n toolName: string\n }\n}\n\n/**\n * Credits calculation option - can be fixed amount or dynamic function\n */\n/**\n * Credits option: fixed bigint or a function receiving {@link CreditsContext}.\n */\nexport type CreditsOption = bigint | ((ctx: CreditsContext) => bigint)\n\n/**\n * Configuration options for paywall protection\n */\n/**\n * Unified paywall options for tools, resources and prompts.\n */\nexport interface BasePaywallOptions {\n name: string\n credits?: CreditsOption\n onRedeemError?: 'ignore' | 'propagate'\n /**\n * Optional override for the Nevermined plan to charge against.\n * If omitted, the plan is inferred from the X402 access token.\n */\n planId?: string\n /**\n * Maximum amount of credits to verify during authentication.\n * Defaults to 1n if not specified.\n */\n maxAmount?: bigint\n}\n\nexport interface ToolOptions extends BasePaywallOptions {\n kind: 'tool'\n}\n\nexport interface ResourceOptions extends BasePaywallOptions {\n kind: 'resource'\n}\n\nexport interface PromptOptions extends BasePaywallOptions {\n kind: 'prompt'\n}\n\nexport type PaywallOptions = ToolOptions | ResourceOptions | PromptOptions\n\n/**\n * Options for decorating tools with paywall protection\n */\n// decorate* helpers removed\n\n/**\n * Authentication result from paywall validation\n */\nexport interface AuthResult {\n token: string\n agentId?: string\n logicalUrl: string\n httpUrl?: string\n planId: string\n subscriberAddress: Address\n agentRequest?: StartAgentRequest\n}\n\n/**\n * Context provided to paywall-protected handlers\n */\nexport interface PaywallContext {\n authResult: AuthResult\n credits?: bigint\n planId: string\n subscriberAddress: Address\n agentRequest?: StartAgentRequest\n}\n\n/**\n * MCP integration configuration\n */\nexport interface McpConfig {\n /** Plan ID the server charges against (required). The facilitator is\n * plan-centric: verify/settle resolve everything from the plan + token. */\n planId: string\n /** Agent ID — optional, informational/observability only. */\n agentId?: string\n serverName?: string\n}\n"]}
1
+ {"version":3,"file":"paywall.types.js","sourceRoot":"","sources":["../../../src/mcp/types/paywall.types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * Type definitions for MCP paywall functionality\n */\nimport type { Address, StartAgentRequest } from '../../common/types.js'\n\n/**\n * Context provided to dynamic credits functions\n */\n/**\n * Context provided to dynamic credits functions.\n */\nexport interface CreditsContext {\n args: unknown\n result: any\n request: {\n authHeader: string\n logicalUrl: string\n toolName: string\n }\n}\n\n/**\n * Credits calculation option - can be fixed amount or dynamic function\n */\n/**\n * Credits option: fixed bigint or a function receiving {@link CreditsContext}.\n */\nexport type CreditsOption = bigint | ((ctx: CreditsContext) => bigint)\n\n/**\n * Configuration options for paywall protection\n */\n/**\n * Unified paywall options for tools, resources and prompts.\n */\nexport interface BasePaywallOptions {\n name: string\n credits?: CreditsOption\n onRedeemError?: 'ignore' | 'propagate'\n /**\n * Optional override for the Nevermined plan to charge against.\n * If omitted, the plan is inferred from the X402 access token.\n */\n planId?: string\n /**\n * Maximum amount of credits to verify during authentication.\n * Defaults to 1n if not specified.\n */\n maxAmount?: bigint\n}\n\nexport interface ToolOptions extends BasePaywallOptions {\n kind: 'tool'\n}\n\nexport interface ResourceOptions extends BasePaywallOptions {\n kind: 'resource'\n}\n\nexport interface PromptOptions extends BasePaywallOptions {\n kind: 'prompt'\n}\n\nexport type PaywallOptions = ToolOptions | ResourceOptions | PromptOptions\n\n/**\n * Options for decorating tools with paywall protection\n */\n// decorate* helpers removed\n\n/**\n * Authentication result from paywall validation\n */\nexport interface AuthResult {\n token: string\n agentId?: string\n logicalUrl: string\n httpUrl?: string\n planId: string\n subscriberAddress: Address\n agentRequest?: StartAgentRequest\n}\n\n/**\n * Context provided to paywall-protected handlers\n */\nexport interface PaywallContext {\n authResult: AuthResult\n credits?: bigint\n planId: string\n subscriberAddress: Address\n agentRequest?: StartAgentRequest\n}\n\n/**\n * MCP integration configuration\n */\nexport interface McpConfig {\n /**\n * Plan ID the server charges against. The facilitator is plan-centric:\n * verify/settle resolve everything from the plan + token.\n *\n * Optional because a planId only has to be **resolvable by the time a handler\n * runs**, and a per-tool `options.planId` satisfies that on its own:\n * `PaywallDecorator` resolves `options?.planId ?? this.config.planId` and\n * refuses only when both are absent (`Server misconfiguration: missing\n * planId`). `withPaywall`'s own docblock has always documented that form.\n *\n * It was declared required anyway, which made `configure({ agentId })` a\n * compile error for a server that sets its plan per tool — a configuration\n * the runtime supports and the docs describe. The type was the only one of the\n * three that forbade it.\n *\n * Set it here when one plan covers the whole server; omit it when every\n * paywalled handler passes its own.\n */\n planId?: string\n /** Agent ID — optional, informational/observability only. */\n agentId?: string\n serverName?: string\n}\n"]}
@@ -17,7 +17,7 @@
17
17
  * environment. A caller branching on `instanceof MppError` to mean
18
18
  * "the payment failed" gets exactly that, and no more.
19
19
  */
20
- import type { DelegationConfig, X402TokenOptions } from '../common/types.js';
20
+ import type { DelegationConfig, MppTokenOptions } from '../common/types.js';
21
21
  import type { MppReceipt } from './types.js';
22
22
  /**
23
23
  * Options for {@link mppFetch} / `MppAPI.fetch`.
@@ -139,8 +139,13 @@ export interface MppFetchResult {
139
139
  */
140
140
  paid: boolean;
141
141
  }
142
- /** Mints an MPP access token for a plan. Supplied by `MppAPI`. */
143
- export type MppTokenMinter = (planId: string, agentId?: string, tokenOptions?: X402TokenOptions) => Promise<{
142
+ /**
143
+ * Mints an MPP access token for a plan. Supplied by `MppAPI`.
144
+ *
145
+ * No `tokenVersion`: MPP carries none (nvm-monorepo#3266) — see
146
+ * {@link MppTokenOptions}.
147
+ */
148
+ export type MppTokenMinter = (planId: string, agentId?: string, tokenOptions?: MppTokenOptions) => Promise<{
144
149
  accessToken: string;
145
150
  }>;
146
151
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../src/mpp/fetch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AAI5E,OAAO,KAAK,EAAgB,UAAU,EAAE,MAAM,YAAY,CAAA;AAE1D;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,eAAe;IAC9B,sEAAsE;IACtE,gBAAgB,EAAE,gBAAgB,CAAA;IAClC;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,6EAA6E;IAC7E,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;;;;;;;;;;;OAYG;IACH,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAA;CACtC;AAED;;;;;GAKG;AACH,MAAM,WAAW,cAAc;IAC7B,iEAAiE;IACjE,QAAQ,EAAE,QAAQ,CAAA;IAClB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,UAAU,CAAA;IACpB;;;;;;;;;;;;;;;;;OAiBG;IACH,OAAO,EAAE,OAAO,CAAA;IAChB;;;;;;;OAOG;IACH,oBAAoB,EAAE,MAAM,CAAA;IAC5B;;;;;;;;;;;;;;;;OAgBG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB;;;;;;;;;;;;;OAaG;IACH,IAAI,EAAE,OAAO,CAAA;CACd;AAED,kEA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B;;;;;;;;;;;;;;;;OAgBG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB;;;;;;;;;;;;;OAaG;IACH,IAAI,EAAE,OAAO,CAAA;CACd;AAED;;;;;GAKG;AACH,MAAM,MAAM,cAAc,GAAG,CAC3B,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,MAAM,EAChB,YAAY,CAAC,EAAE,eAAe,KAC3B,OAAO,CAAC;IAAE,WAAW,EAAE,MAAM,CAAA;CAAE,CAAC,CAAA;AAuPrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AACH,wBAAsB,QAAQ,CAC5B,SAAS,EAAE,cAAc,EACzB,KAAK,EAAE,MAAM,GAAG,GAAG,EACnB,IAAI,EAAE,WAAW,GAAG,SAAS,EAC7B,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,cAAc,CAAC,CA0KzB"}
package/dist/mpp/fetch.js CHANGED
@@ -368,6 +368,12 @@ export async function mppFetch(mintToken, input, init, options) {
368
368
  'so the 402 challenge from this endpoint cannot be replayed. Pass a replayable body ' +
369
369
  'instead — a string, Buffer/ArrayBuffer/typed array, URLSearchParams, FormData or Blob.');
370
370
  }
371
+ // No resource/verb binding and no `tokenVersion` here: MPP carries no
372
+ // token version at all (nvm-monorepo#3266). One MPP access token is
373
+ // presented across many challenges — genuinely distinct operations, not
374
+ // retries of one — so a per-token nonce would kill every buyer's second
375
+ // challenge, which is why the two protocols stopped sharing a version
376
+ // ladder. This loop mints a fresh token per credential regardless.
371
377
  const { accessToken } = await mintToken(planId, options.agentId ?? challenge.request.agentId, { delegationConfig: options.delegationConfig });
372
378
  const headers = new Headers(init?.headers ?? {});
373
379
  const existingAuth = headers.get('authorization');