@open-wa/mcp 5.0.0-alpha.7 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md CHANGED
@@ -55,9 +55,9 @@ Licensor hereby grants permission by this license ("License"), free of charge,
55
55
  4. Compliance with Human Rights Laws and Human Rights Principles:
56
56
 
57
57
  a. **Human Rights Laws**. The Software shall not be used by any person or entity for any systems, activities, or other uses that violate any applicable laws, regulations, or rules that protect human, civil, labor, privacy, political, environmental, security, economic, due process, or similar rights (the "Human Rights Laws"). Where the Human Rights Laws of more than one jurisdiction are applicable to the use of the Software, the Human Rights Laws that are most protective of the individuals or groups harmed shall apply.
58
-
58
+
59
59
  b. **Human Rights Principles**. Licensee is advised to consult the articles of the United Nations Universal Declaration of Human Rights (https://www.un.org/en/universal-declaration-human-rights/) and the United Nations Global Compact (https://www.unglobalcompact.org/ what-is-gc/mission/principles) that define recognized principles of international human rights (the "Human Rights Principles"). It is Licensor's express intent that all use of the Software be consistent with Human Rights Principles. If Licensor receives notification or otherwise learns of an alleged violation of any Human Rights Principles relating to Licensee's use of the Software, Licensor may in its discretion and without obligation (i) (a) notify Licensee of such allegation and (b) allow Licensee 90 days from notification under (i)(a) to investigate and respond to Licensor regarding the allegation and (ii) (a) after the earlier of 90 days from notification under (i)(a), or Licensee's response under (i)(b), notify Licensee of License termination and (b) allow Licensee an additional 90 days from notification under (ii)(a) to cease use of the Software.
60
-
60
+
61
61
  c. **Indemnity**. Licensee shall hold harmless and indemnify Licensor against all losses, damages, liabilities, deficiencies, claims, actions, judgments, settlements, interest, awards, penalties, fines, costs, or expenses of whatever kind, including Licensor's reasonable attorneys' fees, arising out of or relating to Licensee's non-compliance with this License or use of the Software in violation of Human Rights Laws or Human Rights Principles. 
62
62
 
63
63
  5. Enforceability: If any portion or provision of this License is determined to be invalid, illegal, or unenforceable by a court of competent jurisdiction, then such invalidity, illegality, or unenforceability shall not affect any other term or provision of this License or invalidate or render unenforceable such term or provision in any other jurisdiction. Upon a determination that any term or provision is invalid, illegal, or unenforceable, to the extent permitted by applicable law, the court may modify this License to affect the original intent of the parties as closely as possible. The section headings are for convenience only and are not intended to affect the construction or interpretation of this License. Any rule of construction to the effect that ambiguities are to be resolved against the drafting party shall not apply in interpreting this License. The language in this License shall be interpreted as to its fair meaning and not strictly for or against any party.
package/README.md CHANGED
@@ -12,8 +12,8 @@ pnpm add @open-wa/mcp
12
12
 
13
13
  ## Documentation
14
14
 
15
- See the [docs site](https://docs.openwa.dev).
15
+ See the [docs site](https://openwa.dev).
16
16
 
17
17
  ## License
18
18
 
19
- [H-DNH V1.0](https://github.com/open-wa/wa-automate-nodejs/blob/main/LICENSE.md) — Hippocratic + Do Not Harm
19
+ [H-DNH 1.1](https://github.com/open-wa/wa-automate-nodejs/blob/master/LICENSE.md) — Hippocratic + Do Not Harm
package/dist/index.cjs CHANGED
@@ -276,6 +276,16 @@ function createHonoMcpAdapter(options) {
276
276
  });
277
277
  server.connect(transport);
278
278
  return {
279
+ /**
280
+ * Mounts the MCP Streamable HTTP endpoint on the provided Hono app.
281
+ *
282
+ * This creates a single endpoint at `path` that handles:
283
+ * - POST: JSON-RPC messages (initialize, tools/list, tools/call)
284
+ * - GET: Server-initiated SSE stream
285
+ * - DELETE: Session termination
286
+ *
287
+ * API-key auth is enforced on every request before delegation to MCP.
288
+ */
279
289
  mount: (app, path) => {
280
290
  app.all(`${path}`, async (c) => {
281
291
  if (config.apiKey) {
@@ -288,6 +298,9 @@ function createHonoMcpAdapter(options) {
288
298
  return await transport.handleRequest(c.req.raw);
289
299
  });
290
300
  },
301
+ /**
302
+ * Cleanly shut down the MCP transport.
303
+ */
291
304
  close: async () => {
292
305
  await transport.close();
293
306
  await server.close();
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["z","Server","ListToolsRequestSchema","CallToolRequestSchema","WebStandardStreamableHTTPServerTransport"],"sources":["../src/tool-naming.ts","../src/manifest.ts","../src/execution/args.ts","../src/execution/invoke.ts","../src/execution/kernel.ts","../src/execution/errors.ts","../src/adapter/hono-mcp.ts"],"sourcesContent":["/**\n * Logic for stable, namespaced MCP tool names.\n */\n\n/**\n * Returns the canonical namespaced tool name for MCP.\n * @example getCanonicalToolName('messages', 'sendText') -> 'messages.sendText'\n */\nexport function getCanonicalToolName(namespace: string, methodName: string): string {\n return `${namespace}.${methodName}`;\n}\n","import { getHttpMethodDefinitions, type HttpMethodDefinition } from '@open-wa/schema/http-manifest';\nimport { getCanonicalToolName } from './tool-naming';\n\n/**\n * MCP-specific projection of a method capability.\n */\nexport interface McpToolDefinition {\n /**\n * The canonical namespaced tool name for MCP.\n * @example 'messages.sendText'\n */\n toolName: string;\n /**\n * The raw function name in the client.\n * @example 'sendText'\n */\n functionName: string;\n /**\n * The namespaced name (method part only).\n * @example 'sendText'\n */\n namespacedName: string;\n /**\n * The namespace this method belongs to.\n * @example 'messages'\n */\n namespace: string;\n /**\n * Human-readable description of the tool.\n */\n description: string;\n /**\n * Zod input schema.\n */\n inputSchema: HttpMethodDefinition['inputSchema'];\n /**\n * Zod output schema.\n */\n outputSchema: HttpMethodDefinition['outputSchema'];\n /**\n * Preserved parameter order for positional resolution.\n */\n parameterOrder: string[];\n /**\n * Known aliases for this method.\n */\n aliases: string[];\n /**\n * Deprecated aliases for this method.\n */\n deprecatedAliases: string[];\n /**\n * Map of payload key aliases to canonical keys.\n */\n keyAliasMap: Record<string, string>;\n /**\n * Optional metadata hints for AI clients.\n */\n annotations?: {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n };\n}\n\n/**\n * Projects the schema registry into a list of canonical MCP tool definitions.\n */\nexport function getMcpToolDefinitions(basePath = '/api'): McpToolDefinition[] {\n return getHttpMethodDefinitions(basePath).map((def) => {\n return {\n toolName: getCanonicalToolName(def.namespace, def.namespacedName),\n functionName: def.functionName,\n namespacedName: def.namespacedName,\n namespace: def.namespace,\n description: def.description,\n inputSchema: def.inputSchema,\n outputSchema: def.outputSchema,\n parameterOrder: def.parameterOrder,\n aliases: def.aliases,\n deprecatedAliases: def.deprecatedAliases,\n keyAliasMap: def.keyAliasMap,\n annotations: {\n title: def.functionName,\n // Hints can be derived from method names or hardcoded metadata in future\n readOnlyHint: def.functionName.startsWith('get') || def.functionName.startsWith('is'),\n },\n };\n });\n}\n","import { normalizeParameterKeys, z, type HttpMethodDefinition } from '@open-wa/schema';\n\nfunction mapArrayArgs(def: HttpMethodDefinition, args: unknown[]): Record<string, unknown> {\n return def.parameterOrder.reduce<Record<string, unknown>>((acc, key, index) => {\n if (index < args.length) {\n acc[key] = args[index];\n }\n\n return acc;\n }, {});\n}\n\n/**\n * Normalizes an input payload into a form suitable for schema validation.\n * Handles:\n * 1. Array-based positional arguments\n * 2. Mixed key aliases (legacy vs canonical)\n * 3. Wrapped 'args' or 'input' properties\n */\nexport function normalizeMethodPayload(def: HttpMethodDefinition, payload: unknown): any {\n if (Array.isArray(payload)) {\n return normalizeParameterKeys(mapArrayArgs(def, payload), def.keyAliasMap);\n }\n\n if (!payload || typeof payload !== 'object') {\n return {};\n }\n\n const record = payload as Record<string, unknown>;\n\n if ('args' in record) {\n const args = record.args;\n\n if (Array.isArray(args)) {\n return normalizeParameterKeys(mapArrayArgs(def, args), def.keyAliasMap);\n }\n\n if (args && typeof args === 'object') {\n return normalizeParameterKeys(args as Record<string, any>, def.keyAliasMap);\n }\n }\n\n if (record.input && typeof record.input === 'object' && !Array.isArray(record.input)) {\n return normalizeParameterKeys(record.input as Record<string, any>, def.keyAliasMap);\n }\n\n if (def.inputSchema instanceof z.ZodObject) {\n const knownKeys = new Set(Object.keys(def.inputSchema.shape));\n const filtered = Object.fromEntries(\n Object.entries(record).filter(([key]) => knownKeys.has(key))\n );\n\n if (Object.keys(filtered).length > 0) {\n return normalizeParameterKeys(filtered, def.keyAliasMap);\n }\n }\n\n return normalizeParameterKeys(record, def.keyAliasMap);\n}\n","export interface ClientMethodDefinitionLike {\n functionName: string;\n parameterOrder: string[];\n wapiOverride?: string;\n}\n\n/**\n * Invokes a client method by resolving its implementation from the client instance\n * and mapping the payload to positional arguments if necessary.\n */\nexport async function invokeClientMethod(\n client: Record<string, (...args: any[]) => Promise<any> | any> | undefined,\n def: ClientMethodDefinitionLike,\n payload: unknown\n): Promise<any> {\n if (!client) {\n throw new Error('Client not initialized');\n }\n\n const method = client[def.functionName] ?? (def.wapiOverride ? client[def.wapiOverride] : undefined);\n\n if (typeof method !== 'function') {\n throw new Error(`Method ${def.functionName} not implemented on Client`);\n }\n\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {\n return await method.call(client);\n }\n\n const resolvedArgs = def.parameterOrder.map((key) => (payload as Record<string, unknown>)[key]);\n return await method.call(client, ...resolvedArgs);\n}\n","import type { HttpMethodDefinition } from '@open-wa/schema';\nimport { normalizeMethodPayload } from './args';\nimport { invokeClientMethod } from './invoke';\n\n/**\n * Context required to execute an Open-WA capability via any transport.\n */\nexport interface ExecutionContext {\n /**\n * The active client instance or proxy.\n */\n client: Record<string, (...args: any[]) => Promise<any> | any> | undefined;\n /**\n * The metadata definition for the method being invoked.\n */\n definition: HttpMethodDefinition;\n /**\n * The raw input payload (merged query + body, or MCP arguments).\n */\n payload: Record<string, unknown>;\n /**\n * Optional diagnostic emitter for logging.\n */\n elasticEmitter?: {\n log: (data: any) => void;\n };\n /**\n * The unique session identifier.\n */\n sessionId: string;\n}\n\n/**\n * Standardized result of a capability execution.\n */\nexport interface ExecutionResult<T = any> {\n success: boolean;\n data?: T;\n error?: string;\n details?: any;\n status: number;\n}\n\n/**\n * The shared execution kernel for Open-WA capabilities.\n * Ensures strict parity between HTTP API and MCP transport by centralizing\n * normalization, validation, and invocation logic.\n */\nexport async function executeCapability(\n ctx: ExecutionContext\n): Promise<ExecutionResult> {\n const { client, definition, payload, elasticEmitter, sessionId } = ctx;\n const startTime = Date.now();\n const methodName = definition.functionName;\n\n try {\n // 1. Normalize aliases and legacy keys\n const normalizedPayload = normalizeMethodPayload(definition, payload);\n\n // 2. Validate against Zod schema (strict)\n const validated = await definition.inputSchema.parseAsync(normalizedPayload);\n\n // 3. Invoke the client method with positional argument resolution\n const result = await invokeClientMethod(client, definition, validated);\n\n // 4. Log successful execution to monitoring if available\n elasticEmitter?.log({\n level: 'info',\n component: 'api',\n method: methodName,\n sessionId,\n duration: Date.now() - startTime,\n statusCode: 200,\n message: `Successfully executed ${methodName}`,\n });\n\n return {\n success: true,\n data: result,\n status: 200,\n };\n } catch (error: any) {\n const isValidationError = error?.name === 'ZodError';\n const status = isValidationError ? 400 : 500;\n\n // Log failure to monitoring\n elasticEmitter?.log({\n level: 'error',\n component: 'api',\n method: methodName,\n sessionId,\n duration: Date.now() - startTime,\n statusCode: status,\n message: error?.message || 'Internal Server Error',\n });\n\n return {\n success: false,\n error: isValidationError ? 'Validation Error' : (error?.message || 'Internal Server Error'),\n details: isValidationError ? error.issues : undefined,\n status,\n };\n }\n}\n","/**\n * MCP execution error types.\n *\n * Maintains the separation between protocol-level errors\n * (JSON-RPC envelope issues) and tool-level errors\n * (open-wa runtime invocation failures).\n */\n\n/**\n * A tool execution error from the open-wa runtime.\n * This should be surfaced as `isError: true` in MCP tool results,\n * NOT as a JSON-RPC protocol error.\n */\nexport class ToolExecutionError extends Error {\n public readonly statusCode: number;\n public readonly details?: unknown;\n\n constructor(message: string, statusCode = 500, details?: unknown) {\n super(message);\n this.name = 'ToolExecutionError';\n this.statusCode = statusCode;\n this.details = details;\n }\n}\n\n/**\n * A validation error from Zod schema parsing.\n * This should be surfaced as `isError: true` in MCP tool results\n * with the validation details attached.\n */\nexport class ToolValidationError extends ToolExecutionError {\n constructor(message: string, details?: unknown) {\n super(message, 400, details);\n this.name = 'ToolValidationError';\n }\n}\n\n/**\n * Thrown when the client/session is not ready for execution.\n */\nexport class SessionNotReadyError extends ToolExecutionError {\n constructor(message = 'Session is not connected or ready for execution') {\n super(message, 503);\n this.name = 'SessionNotReadyError';\n }\n}\n\n/**\n * Thrown when authentication is missing or invalid.\n */\nexport class AuthenticationError extends ToolExecutionError {\n constructor(message = 'Authentication required. Provide a valid API key.') {\n super(message, 401);\n this.name = 'AuthenticationError';\n }\n}\n","import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport type { Hono, Context } from 'hono';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport type { Config } from '@open-wa/schema';\nimport { getMcpToolDefinitions } from '../manifest';\nimport { executeCapability } from '../execution/kernel';\n\nexport interface HonoMcpAdapterOptions {\n config: Config;\n /**\n * Getter for the active client instance.\n */\n clientSource: () => Record<string, any> | undefined;\n /**\n * Optional logging emitter.\n */\n elasticEmitter?: {\n log: (data: any) => void;\n };\n /**\n * Base path for tool documentation links.\n */\n basePath?: string;\n /**\n * Getter for session readiness state.\n * Used for lifecycle gating parity with HTTP transport.\n */\n isSessionConnected?: () => boolean;\n}\n\n/**\n * Creates an MCP adapter using the Streamable HTTP transport (single-endpoint).\n *\n * open-wa product decision:\n * hosted MCP is Easy API-only and unavailable through createClient()\n *\n * This adapter:\n * - Uses WebStandardStreamableHTTPServerTransport for a single-endpoint /mcp shape\n * - Enforces Easy API API-key auth on every request\n * - Gates tool execution on session readiness (parity with HTTP transport)\n * - Returns protocol errors for malformed protocol requests\n * - Returns tool-level errors for open-wa execution failures\n */\nexport function createHonoMcpAdapter(options: HonoMcpAdapterOptions) {\n const { config, clientSource, elasticEmitter, basePath = '/api', isSessionConnected } = options;\n const toolDefinitions = getMcpToolDefinitions(basePath);\n const toolMap = new Map(toolDefinitions.map((d) => [d.toolName, d]));\n\n const server = new Server(\n {\n name: 'open-wa',\n version: '5.0.0',\n },\n {\n capabilities: {\n tools: {},\n },\n }\n );\n\n // ── tools/list ──────────────────────────────────────────────────────\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: toolDefinitions.map((def) => ({\n name: def.toolName,\n description: def.description,\n inputSchema: zodToJsonSchema(def.inputSchema) as any,\n })),\n };\n });\n\n // ── tools/call ──────────────────────────────────────────────────────\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n const definition = toolMap.get(name);\n\n if (!definition) {\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `Unknown tool: ${name}. Use tools/list to discover available tools.`,\n },\n ],\n };\n }\n\n // ── Lifecycle/readiness gate (parity with HTTP transport) ──────\n if (isSessionConnected && !isSessionConnected()) {\n if (config.apiLifecycle !== 'immediate') {\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: 'Session is not connected or ready. Tool execution is blocked until the session is fully ready.',\n },\n ],\n };\n }\n }\n\n const result = await executeCapability({\n client: clientSource(),\n definition: definition as any,\n payload: (args as Record<string, unknown>) || {},\n elasticEmitter,\n sessionId: config.sessionId,\n });\n\n if (result.success) {\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result.data, null, 2),\n },\n ],\n };\n }\n\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: result.error || 'Internal Execution Error',\n },\n ],\n };\n });\n\n // ── Streamable HTTP transport ───────────────────────────────────────\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: () => crypto.randomUUID(),\n onsessioninitialized: (sessionId: string) => {\n elasticEmitter?.log({\n level: 'info',\n component: 'mcp',\n message: `MCP session initialized: ${sessionId}`,\n sessionId: config.sessionId,\n });\n },\n onsessionclosed: (sessionId: string) => {\n elasticEmitter?.log({\n level: 'info',\n component: 'mcp',\n message: `MCP session closed: ${sessionId}`,\n sessionId: config.sessionId,\n });\n },\n });\n\n // Connect the server to the transport immediately\n server.connect(transport);\n\n return {\n /**\n * Mounts the MCP Streamable HTTP endpoint on the provided Hono app.\n *\n * This creates a single endpoint at `path` that handles:\n * - POST: JSON-RPC messages (initialize, tools/list, tools/call)\n * - GET: Server-initiated SSE stream\n * - DELETE: Session termination\n *\n * API-key auth is enforced on every request before delegation to MCP.\n */\n mount: (app: Hono, path: string) => {\n app.all(`${path}`, async (c: Context) => {\n // ── API-key auth enforcement ───────────────────────────────\n // MCP inherits Easy API auth boundary. No key = no access.\n if (config.apiKey) {\n const headerKey =\n c.req.header('X-API-Key') ||\n c.req.header('api_key') ||\n c.req.header('key');\n const resolvedKey = headerKey;\n\n if (!resolvedKey || resolvedKey !== config.apiKey) {\n return c.json(\n { error: 'Unauthorized', details: 'Invalid or missing API key for MCP endpoint' },\n 401,\n );\n }\n }\n\n // ── Delegate to Streamable HTTP transport ──────────────────\n const response = await transport.handleRequest(c.req.raw);\n return response;\n });\n },\n\n /**\n * Cleanly shut down the MCP transport.\n */\n close: async () => {\n await transport.close();\n await server.close();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAQA,SAAgB,qBAAqB,WAAmB,YAA4B;AAClF,QAAO,GAAG,UAAU,GAAG;;;;;;;AC4DzB,SAAgB,sBAAsB,WAAW,QAA6B;AAC5E,SAAA,GAAA,8BAAA,0BAAgC,SAAS,CAAC,KAAK,QAAQ;AACrD,SAAO;GACL,UAAU,qBAAqB,IAAI,WAAW,IAAI,eAAe;GACjE,cAAc,IAAI;GAClB,gBAAgB,IAAI;GACpB,WAAW,IAAI;GACf,aAAa,IAAI;GACjB,aAAa,IAAI;GACjB,cAAc,IAAI;GAClB,gBAAgB,IAAI;GACpB,SAAS,IAAI;GACb,mBAAmB,IAAI;GACvB,aAAa,IAAI;GACjB,aAAa;IACX,OAAO,IAAI;IAEX,cAAc,IAAI,aAAa,WAAW,MAAM,IAAI,IAAI,aAAa,WAAW,KAAK;IACtF;GACF;GACD;;;;ACvFJ,SAAS,aAAa,KAA2B,MAA0C;AACzF,QAAO,IAAI,eAAe,QAAiC,KAAK,KAAK,UAAU;AAC7E,MAAI,QAAQ,KAAK,OACf,KAAI,OAAO,KAAK;AAGlB,SAAO;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MAAM,kBAAkB;GACrC,QAAQ,cAAc;GACV;GACZ,SAAU,QAAoC,EAAE;GAChD;GACA,WAAW,OAAO;GACnB,CAAC;AAEF,MAAI,OAAO,QACT,QAAO,EACL,SAAS,CACP;GACE,MAAM;GACN,MAAM,KAAK,UAAU,OAAO,MAAM,MAAM,EAAE;GAC3C,CACF,EACF;AAGH,SAAO;GACL,SAAS;GACT,SAAS,CACP;IACE,MAAM;IACN,MAAM,OAAO,SAAS;IACvB,CACF;GACF;GACD;CAGF,MAAM,YAAY,IAAIC,8DAAAA,yCAAyC;EAC7D,0BAA0B,OAAO,YAAY;EAC7C,uBAAuB,cAAsB;AAC3C,mBAAgB,IAAI;IAClB,OAAO;IACP,WAAW;IACX,SAAS,4BAA4B;IACrC,WAAW,OAAO;IACnB,CAAC;;EAEJ,kBAAkB,cAAsB;AACtC,mBAAgB,IAAI;IAClB,OAAO;IACP,WAAW;IACX,SAAS,uBAAuB;IAChC,WAAW,OAAO;IACnB,CAAC;;EAEL,CAAC;AAGF,QAAO,QAAQ,UAAU;AAEzB,QAAO;EAWL,QAAQ,KAAW,SAAiB;AAClC,OAAI,IAAI,GAAG,QAAQ,OAAO,MAAe;AAGvC,QAAI,OAAO,QAAQ;KAKjB,MAAM,cAHJ,EAAE,IAAI,OAAO,YAAY,IACzB,EAAE,IAAI,OAAO,UAAU,IACvB,EAAE,IAAI,OAAO,MAAM;AAGrB,SAAI,CAAC,eAAe,gBAAgB,OAAO,OACzC,QAAO,EAAE,KACP;MAAE,OAAO;MAAgB,SAAS;MAA+C,EACjF,IACD;;AAML,WADiB,MAAM,UAAU,cAAc,EAAE,IAAI,IAAI;KAEzD;;EAMJ,OAAO,YAAY;AACjB,SAAM,UAAU,OAAO;AACvB,SAAM,OAAO,OAAO;;EAEvB"}
1
+ {"version":3,"file":"index.cjs","names":["getHttpMethodDefinitions","normalizeParameterKeys","z","Server","ListToolsRequestSchema","zodToJsonSchema","CallToolRequestSchema","WebStandardStreamableHTTPServerTransport"],"sources":["../src/tool-naming.ts","../src/manifest.ts","../src/execution/args.ts","../src/execution/invoke.ts","../src/execution/kernel.ts","../src/execution/errors.ts","../src/adapter/hono-mcp.ts"],"sourcesContent":["/**\n * Logic for stable, namespaced MCP tool names.\n */\n\n/**\n * Returns the canonical namespaced tool name for MCP.\n * @example getCanonicalToolName('messages', 'sendText') -> 'messages.sendText'\n */\nexport function getCanonicalToolName(namespace: string, methodName: string): string {\n return `${namespace}.${methodName}`;\n}\n","import { getHttpMethodDefinitions, type HttpMethodDefinition } from '@open-wa/schema/http-manifest';\nimport { getCanonicalToolName } from './tool-naming';\n\n/**\n * MCP-specific projection of a method capability.\n */\nexport interface McpToolDefinition {\n /**\n * The canonical namespaced tool name for MCP.\n * @example 'messages.sendText'\n */\n toolName: string;\n /**\n * The raw function name in the client.\n * @example 'sendText'\n */\n functionName: string;\n /**\n * The namespaced name (method part only).\n * @example 'sendText'\n */\n namespacedName: string;\n /**\n * The namespace this method belongs to.\n * @example 'messages'\n */\n namespace: string;\n /**\n * Human-readable description of the tool.\n */\n description: string;\n /**\n * Zod input schema.\n */\n inputSchema: HttpMethodDefinition['inputSchema'];\n /**\n * Zod output schema.\n */\n outputSchema: HttpMethodDefinition['outputSchema'];\n /**\n * Preserved parameter order for positional resolution.\n */\n parameterOrder: string[];\n /**\n * Known aliases for this method.\n */\n aliases: string[];\n /**\n * Deprecated aliases for this method.\n */\n deprecatedAliases: string[];\n /**\n * Map of payload key aliases to canonical keys.\n */\n keyAliasMap: Record<string, string>;\n /**\n * Optional metadata hints for AI clients.\n */\n annotations?: {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n };\n}\n\n/**\n * Projects the schema registry into a list of canonical MCP tool definitions.\n */\nexport function getMcpToolDefinitions(basePath = '/api'): McpToolDefinition[] {\n return getHttpMethodDefinitions(basePath).map((def) => {\n return {\n toolName: getCanonicalToolName(def.namespace, def.namespacedName),\n functionName: def.functionName,\n namespacedName: def.namespacedName,\n namespace: def.namespace,\n description: def.description,\n inputSchema: def.inputSchema,\n outputSchema: def.outputSchema,\n parameterOrder: def.parameterOrder,\n aliases: def.aliases,\n deprecatedAliases: def.deprecatedAliases,\n keyAliasMap: def.keyAliasMap,\n annotations: {\n title: def.functionName,\n // Hints can be derived from method names or hardcoded metadata in future\n readOnlyHint: def.functionName.startsWith('get') || def.functionName.startsWith('is'),\n },\n };\n });\n}\n","import { normalizeParameterKeys, z, type HttpMethodDefinition } from '@open-wa/schema';\n\nfunction mapArrayArgs(def: HttpMethodDefinition, args: unknown[]): Record<string, unknown> {\n return def.parameterOrder.reduce<Record<string, unknown>>((acc, key, index) => {\n if (index < args.length) {\n acc[key] = args[index];\n }\n\n return acc;\n }, {});\n}\n\n/**\n * Normalizes an input payload into a form suitable for schema validation.\n * Handles:\n * 1. Array-based positional arguments\n * 2. Mixed key aliases (legacy vs canonical)\n * 3. Wrapped 'args' or 'input' properties\n */\nexport function normalizeMethodPayload(def: HttpMethodDefinition, payload: unknown): any {\n if (Array.isArray(payload)) {\n return normalizeParameterKeys(mapArrayArgs(def, payload), def.keyAliasMap);\n }\n\n if (!payload || typeof payload !== 'object') {\n return {};\n }\n\n const record = payload as Record<string, unknown>;\n\n if ('args' in record) {\n const args = record.args;\n\n if (Array.isArray(args)) {\n return normalizeParameterKeys(mapArrayArgs(def, args), def.keyAliasMap);\n }\n\n if (args && typeof args === 'object') {\n return normalizeParameterKeys(args as Record<string, any>, def.keyAliasMap);\n }\n }\n\n if (record.input && typeof record.input === 'object' && !Array.isArray(record.input)) {\n return normalizeParameterKeys(record.input as Record<string, any>, def.keyAliasMap);\n }\n\n if (def.inputSchema instanceof z.ZodObject) {\n const knownKeys = new Set(Object.keys(def.inputSchema.shape));\n const filtered = Object.fromEntries(\n Object.entries(record).filter(([key]) => knownKeys.has(key))\n );\n\n if (Object.keys(filtered).length > 0) {\n return normalizeParameterKeys(filtered, def.keyAliasMap);\n }\n }\n\n return normalizeParameterKeys(record, def.keyAliasMap);\n}\n","export interface ClientMethodDefinitionLike {\n functionName: string;\n parameterOrder: string[];\n wapiOverride?: string;\n}\n\n/**\n * Invokes a client method by resolving its implementation from the client instance\n * and mapping the payload to positional arguments if necessary.\n */\nexport async function invokeClientMethod(\n client: Record<string, (...args: any[]) => Promise<any> | any> | undefined,\n def: ClientMethodDefinitionLike,\n payload: unknown\n): Promise<any> {\n if (!client) {\n throw new Error('Client not initialized');\n }\n\n const method = client[def.functionName] ?? (def.wapiOverride ? client[def.wapiOverride] : undefined);\n\n if (typeof method !== 'function') {\n throw new Error(`Method ${def.functionName} not implemented on Client`);\n }\n\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {\n return await method.call(client);\n }\n\n const resolvedArgs = def.parameterOrder.map((key) => (payload as Record<string, unknown>)[key]);\n return await method.call(client, ...resolvedArgs);\n}\n","import type { HttpMethodDefinition } from '@open-wa/schema';\nimport { normalizeMethodPayload } from './args';\nimport { invokeClientMethod } from './invoke';\n\n/**\n * Context required to execute an Open-WA capability via any transport.\n */\nexport interface ExecutionContext {\n /**\n * The active client instance or proxy.\n */\n client: Record<string, (...args: any[]) => Promise<any> | any> | undefined;\n /**\n * The metadata definition for the method being invoked.\n */\n definition: HttpMethodDefinition;\n /**\n * The raw input payload (merged query + body, or MCP arguments).\n */\n payload: Record<string, unknown>;\n /**\n * Optional diagnostic emitter for logging.\n */\n elasticEmitter?: {\n log: (data: any) => void;\n };\n /**\n * The unique session identifier.\n */\n sessionId: string;\n}\n\n/**\n * Standardized result of a capability execution.\n */\nexport interface ExecutionResult<T = any> {\n success: boolean;\n data?: T;\n error?: string;\n details?: any;\n status: number;\n}\n\n/**\n * The shared execution kernel for Open-WA capabilities.\n * Ensures strict parity between HTTP API and MCP transport by centralizing\n * normalization, validation, and invocation logic.\n */\nexport async function executeCapability(\n ctx: ExecutionContext\n): Promise<ExecutionResult> {\n const { client, definition, payload, elasticEmitter, sessionId } = ctx;\n const startTime = Date.now();\n const methodName = definition.functionName;\n\n try {\n // 1. Normalize aliases and legacy keys\n const normalizedPayload = normalizeMethodPayload(definition, payload);\n\n // 2. Validate against Zod schema (strict)\n const validated = await definition.inputSchema.parseAsync(normalizedPayload);\n\n // 3. Invoke the client method with positional argument resolution\n const result = await invokeClientMethod(client, definition, validated);\n\n // 4. Log successful execution to monitoring if available\n elasticEmitter?.log({\n level: 'info',\n component: 'api',\n method: methodName,\n sessionId,\n duration: Date.now() - startTime,\n statusCode: 200,\n message: `Successfully executed ${methodName}`,\n });\n\n return {\n success: true,\n data: result,\n status: 200,\n };\n } catch (error: any) {\n const isValidationError = error?.name === 'ZodError';\n const status = isValidationError ? 400 : 500;\n\n // Log failure to monitoring\n elasticEmitter?.log({\n level: 'error',\n component: 'api',\n method: methodName,\n sessionId,\n duration: Date.now() - startTime,\n statusCode: status,\n message: error?.message || 'Internal Server Error',\n });\n\n return {\n success: false,\n error: isValidationError ? 'Validation Error' : (error?.message || 'Internal Server Error'),\n details: isValidationError ? error.issues : undefined,\n status,\n };\n }\n}\n","/**\n * MCP execution error types.\n *\n * Maintains the separation between protocol-level errors\n * (JSON-RPC envelope issues) and tool-level errors\n * (open-wa runtime invocation failures).\n */\n\n/**\n * A tool execution error from the open-wa runtime.\n * This should be surfaced as `isError: true` in MCP tool results,\n * NOT as a JSON-RPC protocol error.\n */\nexport class ToolExecutionError extends Error {\n public readonly statusCode: number;\n public readonly details?: unknown;\n\n constructor(message: string, statusCode = 500, details?: unknown) {\n super(message);\n this.name = 'ToolExecutionError';\n this.statusCode = statusCode;\n this.details = details;\n }\n}\n\n/**\n * A validation error from Zod schema parsing.\n * This should be surfaced as `isError: true` in MCP tool results\n * with the validation details attached.\n */\nexport class ToolValidationError extends ToolExecutionError {\n constructor(message: string, details?: unknown) {\n super(message, 400, details);\n this.name = 'ToolValidationError';\n }\n}\n\n/**\n * Thrown when the client/session is not ready for execution.\n */\nexport class SessionNotReadyError extends ToolExecutionError {\n constructor(message = 'Session is not connected or ready for execution') {\n super(message, 503);\n this.name = 'SessionNotReadyError';\n }\n}\n\n/**\n * Thrown when authentication is missing or invalid.\n */\nexport class AuthenticationError extends ToolExecutionError {\n constructor(message = 'Authentication required. Provide a valid API key.') {\n super(message, 401);\n this.name = 'AuthenticationError';\n }\n}\n","import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport type { Hono, Context } from 'hono';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport type { Config } from '@open-wa/schema';\nimport { getMcpToolDefinitions } from '../manifest';\nimport { executeCapability } from '../execution/kernel';\n\nexport interface HonoMcpAdapterOptions {\n config: Config;\n /**\n * Getter for the active client instance.\n */\n clientSource: () => Record<string, any> | undefined;\n /**\n * Optional logging emitter.\n */\n elasticEmitter?: {\n log: (data: any) => void;\n };\n /**\n * Base path for tool documentation links.\n */\n basePath?: string;\n /**\n * Getter for session readiness state.\n * Used for lifecycle gating parity with HTTP transport.\n */\n isSessionConnected?: () => boolean;\n}\n\n/**\n * Creates an MCP adapter using the Streamable HTTP transport (single-endpoint).\n *\n * open-wa product decision:\n * hosted MCP is Easy API-only and unavailable through createClient()\n *\n * This adapter:\n * - Uses WebStandardStreamableHTTPServerTransport for a single-endpoint /mcp shape\n * - Enforces Easy API API-key auth on every request\n * - Gates tool execution on session readiness (parity with HTTP transport)\n * - Returns protocol errors for malformed protocol requests\n * - Returns tool-level errors for open-wa execution failures\n */\nexport function createHonoMcpAdapter(options: HonoMcpAdapterOptions) {\n const { config, clientSource, elasticEmitter, basePath = '/api', isSessionConnected } = options;\n const toolDefinitions = getMcpToolDefinitions(basePath);\n const toolMap = new Map(toolDefinitions.map((d) => [d.toolName, d]));\n\n const server = new Server(\n {\n name: 'open-wa',\n version: '5.0.0',\n },\n {\n capabilities: {\n tools: {},\n },\n }\n );\n\n // ── tools/list ──────────────────────────────────────────────────────\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: toolDefinitions.map((def) => ({\n name: def.toolName,\n description: def.description,\n inputSchema: zodToJsonSchema(def.inputSchema) as any,\n })),\n };\n });\n\n // ── tools/call ──────────────────────────────────────────────────────\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n const definition = toolMap.get(name);\n\n if (!definition) {\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: `Unknown tool: ${name}. Use tools/list to discover available tools.`,\n },\n ],\n };\n }\n\n // ── Lifecycle/readiness gate (parity with HTTP transport) ──────\n if (isSessionConnected && !isSessionConnected()) {\n if (config.apiLifecycle !== 'immediate') {\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: 'Session is not connected or ready. Tool execution is blocked until the session is fully ready.',\n },\n ],\n };\n }\n }\n\n const result = await executeCapability({\n client: clientSource(),\n definition: definition as any,\n payload: (args as Record<string, unknown>) || {},\n elasticEmitter,\n sessionId: config.sessionId,\n });\n\n if (result.success) {\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result.data, null, 2),\n },\n ],\n };\n }\n\n return {\n isError: true,\n content: [\n {\n type: 'text' as const,\n text: result.error || 'Internal Execution Error',\n },\n ],\n };\n });\n\n // ── Streamable HTTP transport ───────────────────────────────────────\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: () => crypto.randomUUID(),\n onsessioninitialized: (sessionId: string) => {\n elasticEmitter?.log({\n level: 'info',\n component: 'mcp',\n message: `MCP session initialized: ${sessionId}`,\n sessionId: config.sessionId,\n });\n },\n onsessionclosed: (sessionId: string) => {\n elasticEmitter?.log({\n level: 'info',\n component: 'mcp',\n message: `MCP session closed: ${sessionId}`,\n sessionId: config.sessionId,\n });\n },\n });\n\n // Connect the server to the transport immediately\n server.connect(transport);\n\n return {\n /**\n * Mounts the MCP Streamable HTTP endpoint on the provided Hono app.\n *\n * This creates a single endpoint at `path` that handles:\n * - POST: JSON-RPC messages (initialize, tools/list, tools/call)\n * - GET: Server-initiated SSE stream\n * - DELETE: Session termination\n *\n * API-key auth is enforced on every request before delegation to MCP.\n */\n mount: (app: Hono, path: string) => {\n app.all(`${path}`, async (c: Context) => {\n // ── API-key auth enforcement ───────────────────────────────\n // MCP inherits Easy API auth boundary. No key = no access.\n if (config.apiKey) {\n const headerKey =\n c.req.header('X-API-Key') ||\n c.req.header('api_key') ||\n c.req.header('key');\n const resolvedKey = headerKey;\n\n if (!resolvedKey || resolvedKey !== config.apiKey) {\n return c.json(\n { error: 'Unauthorized', details: 'Invalid or missing API key for MCP endpoint' },\n 401,\n );\n }\n }\n\n // ── Delegate to Streamable HTTP transport ──────────────────\n const response = await transport.handleRequest(c.req.raw);\n return response;\n });\n },\n\n /**\n * Cleanly shut down the MCP transport.\n */\n close: async () => {\n await transport.close();\n await server.close();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAQA,SAAgB,qBAAqB,WAAmB,YAA4B;CAClF,OAAO,GAAG,UAAU,GAAG;AACzB;;;;;;AC2DA,SAAgB,sBAAsB,WAAW,QAA6B;CAC5E,QAAA,GAAOA,8BAAAA,yBAAAA,CAAyB,QAAQ,CAAC,CAAC,KAAK,QAAQ;EACrD,OAAO;GACL,UAAU,qBAAqB,IAAI,WAAW,IAAI,cAAc;GAChE,cAAc,IAAI;GAClB,gBAAgB,IAAI;GACpB,WAAW,IAAI;GACf,aAAa,IAAI;GACjB,aAAa,IAAI;GACjB,cAAc,IAAI;GAClB,gBAAgB,IAAI;GACpB,SAAS,IAAI;GACb,mBAAmB,IAAI;GACvB,aAAa,IAAI;GACjB,aAAa;IACX,OAAO,IAAI;IAEX,cAAc,IAAI,aAAa,WAAW,KAAK,KAAK,IAAI,aAAa,WAAW,IAAI;GACtF;EACF;CACF,CAAC;AACH;;;ACxFA,SAAS,aAAa,KAA2B,MAA0C;CACzF,OAAO,IAAI,eAAe,QAAiC,KAAK,K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A,OAAO,MADgB,UAAU,cAAc,EAAE,IAAI,GAAG;GAE1D,CAAC;EACH;;;;EAKA,OAAO,YAAY;GACjB,MAAM,UAAU,MAAM;GACtB,MAAM,OAAO,MAAM;EACrB;CACF;AACF"}
package/dist/index.d.cts CHANGED
@@ -1,63 +1,19 @@
1
1
  import { HttpMethodDefinition } from "@open-wa/schema/http-manifest";
2
2
  import { Config, HttpMethodDefinition as HttpMethodDefinition$1 } from "@open-wa/schema";
3
3
  import { Hono } from "hono";
4
-
5
4
  //#region src/manifest.d.ts
6
- /**
7
- * MCP-specific projection of a method capability.
8
- */
9
- interface McpToolDefinition {
10
- /**
11
- * The canonical namespaced tool name for MCP.
12
- * @example 'messages.sendText'
13
- */
5
+ export interface McpToolDefinition {
14
6
  toolName: string;
15
- /**
16
- * The raw function name in the client.
17
- * @example 'sendText'
18
- */
19
7
  functionName: string;
20
- /**
21
- * The namespaced name (method part only).
22
- * @example 'sendText'
23
- */
24
8
  namespacedName: string;
25
- /**
26
- * The namespace this method belongs to.
27
- * @example 'messages'
28
- */
29
9
  namespace: string;
30
- /**
31
- * Human-readable description of the tool.
32
- */
33
10
  description: string;
34
- /**
35
- * Zod input schema.
36
- */
37
11
  inputSchema: HttpMethodDefinition['inputSchema'];
38
- /**
39
- * Zod output schema.
40
- */
41
12
  outputSchema: HttpMethodDefinition['outputSchema'];
42
- /**
43
- * Preserved parameter order for positional resolution.
44
- */
45
13
  parameterOrder: string[];
46
- /**
47
- * Known aliases for this method.
48
- */
49
14
  aliases: string[];
50
- /**
51
- * Deprecated aliases for this method.
52
- */
53
15
  deprecatedAliases: string[];
54
- /**
55
- * Map of payload key aliases to canonical keys.
56
- */
57
16
  keyAliasMap: Record<string, string>;
58
- /**
59
- * Optional metadata hints for AI clients.
60
- */
61
17
  annotations?: {
62
18
  title?: string;
63
19
  readOnlyHint?: boolean;
@@ -65,180 +21,70 @@ interface McpToolDefinition {
65
21
  idempotentHint?: boolean;
66
22
  };
67
23
  }
68
- /**
69
- * Projects the schema registry into a list of canonical MCP tool definitions.
70
- */
71
- declare function getMcpToolDefinitions(basePath?: string): McpToolDefinition[];
24
+ export declare function getMcpToolDefinitions(basePath?: string): McpToolDefinition[];
72
25
  //#endregion
73
26
  //#region src/tool-naming.d.ts
74
- /**
75
- * Logic for stable, namespaced MCP tool names.
76
- */
77
- /**
78
- * Returns the canonical namespaced tool name for MCP.
79
- * @example getCanonicalToolName('messages', 'sendText') -> 'messages.sendText'
80
- */
81
- declare function getCanonicalToolName(namespace: string, methodName: string): string;
27
+ export declare function getCanonicalToolName(namespace: string, methodName: string): string;
82
28
  //#endregion
83
29
  //#region src/execution/kernel.d.ts
84
- /**
85
- * Context required to execute an Open-WA capability via any transport.
86
- */
87
- interface ExecutionContext {
88
- /**
89
- * The active client instance or proxy.
90
- */
30
+ export interface ExecutionContext {
91
31
  client: Record<string, (...args: any[]) => Promise<any> | any> | undefined;
92
- /**
93
- * The metadata definition for the method being invoked.
94
- */
95
32
  definition: HttpMethodDefinition$1;
96
- /**
97
- * The raw input payload (merged query + body, or MCP arguments).
98
- */
99
33
  payload: Record<string, unknown>;
100
- /**
101
- * Optional diagnostic emitter for logging.
102
- */
103
34
  elasticEmitter?: {
104
35
  log: (data: any) => void;
105
36
  };
106
- /**
107
- * The unique session identifier.
108
- */
109
37
  sessionId: string;
110
38
  }
111
- /**
112
- * Standardized result of a capability execution.
113
- */
114
- interface ExecutionResult<T = any> {
39
+ export interface ExecutionResult<T = any> {
115
40
  success: boolean;
116
41
  data?: T;
117
42
  error?: string;
118
43
  details?: any;
119
44
  status: number;
120
45
  }
121
- /**
122
- * The shared execution kernel for Open-WA capabilities.
123
- * Ensures strict parity between HTTP API and MCP transport by centralizing
124
- * normalization, validation, and invocation logic.
125
- */
126
- declare function executeCapability(ctx: ExecutionContext): Promise<ExecutionResult>;
46
+ export declare function executeCapability(ctx: ExecutionContext): Promise<ExecutionResult>;
127
47
  //#endregion
128
48
  //#region src/execution/args.d.ts
129
- /**
130
- * Normalizes an input payload into a form suitable for schema validation.
131
- * Handles:
132
- * 1. Array-based positional arguments
133
- * 2. Mixed key aliases (legacy vs canonical)
134
- * 3. Wrapped 'args' or 'input' properties
135
- */
136
- declare function normalizeMethodPayload(def: HttpMethodDefinition$1, payload: unknown): any;
49
+ export declare function normalizeMethodPayload(def: HttpMethodDefinition$1, payload: unknown): any;
137
50
  //#endregion
138
51
  //#region src/execution/invoke.d.ts
139
- interface ClientMethodDefinitionLike {
52
+ export interface ClientMethodDefinitionLike {
140
53
  functionName: string;
141
54
  parameterOrder: string[];
142
55
  wapiOverride?: string;
143
56
  }
144
- /**
145
- * Invokes a client method by resolving its implementation from the client instance
146
- * and mapping the payload to positional arguments if necessary.
147
- */
148
- declare function invokeClientMethod(client: Record<string, (...args: any[]) => Promise<any> | any> | undefined, def: ClientMethodDefinitionLike, payload: unknown): Promise<any>;
57
+ export declare function invokeClientMethod(client: Record<string, (...args: any[]) => Promise<any> | any> | undefined, def: ClientMethodDefinitionLike, payload: unknown): Promise<any>;
149
58
  //#endregion
150
59
  //#region src/execution/errors.d.ts
151
- /**
152
- * MCP execution error types.
153
- *
154
- * Maintains the separation between protocol-level errors
155
- * (JSON-RPC envelope issues) and tool-level errors
156
- * (open-wa runtime invocation failures).
157
- */
158
- /**
159
- * A tool execution error from the open-wa runtime.
160
- * This should be surfaced as `isError: true` in MCP tool results,
161
- * NOT as a JSON-RPC protocol error.
162
- */
163
- declare class ToolExecutionError extends Error {
60
+ export declare class ToolExecutionError extends Error {
164
61
  readonly statusCode: number;
165
62
  readonly details?: unknown;
166
63
  constructor(message: string, statusCode?: number, details?: unknown);
167
64
  }
168
- /**
169
- * A validation error from Zod schema parsing.
170
- * This should be surfaced as `isError: true` in MCP tool results
171
- * with the validation details attached.
172
- */
173
- declare class ToolValidationError extends ToolExecutionError {
65
+ export declare class ToolValidationError extends ToolExecutionError {
174
66
  constructor(message: string, details?: unknown);
175
67
  }
176
- /**
177
- * Thrown when the client/session is not ready for execution.
178
- */
179
- declare class SessionNotReadyError extends ToolExecutionError {
68
+ export declare class SessionNotReadyError extends ToolExecutionError {
180
69
  constructor(message?: string);
181
70
  }
182
- /**
183
- * Thrown when authentication is missing or invalid.
184
- */
185
- declare class AuthenticationError extends ToolExecutionError {
71
+ export declare class AuthenticationError extends ToolExecutionError {
186
72
  constructor(message?: string);
187
73
  }
188
74
  //#endregion
189
75
  //#region src/adapter/hono-mcp.d.ts
190
- interface HonoMcpAdapterOptions {
76
+ export interface HonoMcpAdapterOptions {
191
77
  config: Config;
192
- /**
193
- * Getter for the active client instance.
194
- */
195
78
  clientSource: () => Record<string, any> | undefined;
196
- /**
197
- * Optional logging emitter.
198
- */
199
79
  elasticEmitter?: {
200
80
  log: (data: any) => void;
201
81
  };
202
- /**
203
- * Base path for tool documentation links.
204
- */
205
82
  basePath?: string;
206
- /**
207
- * Getter for session readiness state.
208
- * Used for lifecycle gating parity with HTTP transport.
209
- */
210
83
  isSessionConnected?: () => boolean;
211
84
  }
212
- /**
213
- * Creates an MCP adapter using the Streamable HTTP transport (single-endpoint).
214
- *
215
- * open-wa product decision:
216
- * hosted MCP is Easy API-only and unavailable through createClient()
217
- *
218
- * This adapter:
219
- * - Uses WebStandardStreamableHTTPServerTransport for a single-endpoint /mcp shape
220
- * - Enforces Easy API API-key auth on every request
221
- * - Gates tool execution on session readiness (parity with HTTP transport)
222
- * - Returns protocol errors for malformed protocol requests
223
- * - Returns tool-level errors for open-wa execution failures
224
- */
225
- declare function createHonoMcpAdapter(options: HonoMcpAdapterOptions): {
226
- /**
227
- * Mounts the MCP Streamable HTTP endpoint on the provided Hono app.
228
- *
229
- * This creates a single endpoint at `path` that handles:
230
- * - POST: JSON-RPC messages (initialize, tools/list, tools/call)
231
- * - GET: Server-initiated SSE stream
232
- * - DELETE: Session termination
233
- *
234
- * API-key auth is enforced on every request before delegation to MCP.
235
- */
85
+ export declare function createHonoMcpAdapter(options: HonoMcpAdapterOptions): {
236
86
  mount: (app: Hono, path: string) => void;
237
- /**
238
- * Cleanly shut down the MCP transport.
239
- */
240
87
  close: () => Promise<void>;
241
88
  };
242
89
  //#endregion
243
- export { AuthenticationError, ClientMethodDefinitionLike, ExecutionContext, ExecutionResult, HonoMcpAdapterOptions, McpToolDefinition, SessionNotReadyError, ToolExecutionError, ToolValidationError, createHonoMcpAdapter, executeCapability, getCanonicalToolName, getMcpToolDefinitions, invokeClientMethod, normalizeMethodPayload };
244
90
  //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","names":["HttpMethodDefinition","HttpMethodDefinition"],"sources":["../src/manifest.ts","../src/tool-naming.ts","../src/execution/kernel.ts","../src/execution/args.ts","../src/execution/invoke.ts","../src/execution/errors.ts","../src/adapter/hono-mcp.ts"],"mappings":";;;;iBAMiB;EAKf;EAKA;EAKA;EAKA;EAIA;EAIA,aAAa;EAIb,cAAc;EAId;EAIA;EAIA;EAIA,aAAa;EAIb;IACE;IACA;IACA;IACA;;;wBAOY,sBAAsB,oBAAoB;;;wBC7D1C,qBAAqB,mBAAmB;;;iBCDvC;EAIf,QAAQ,mBAAmB,gBAAgB;EAI3C,YAAYA;EAIZ,SAAS;EAIT;IACE,MAAM;;EAKR;;iBAMe,gBAAgB;EAC/B;EACA,OAAO;EACP;EACA;EACA;;wBAQoB,kBACpB,KAAK,mBACJ,QAAQ;;;wBC/BK,uBAAuB,KAAKC,wBAAsB;;;iBCnBjD;EACf;EACA;EACA;;wBAOoB,mBACpB,QAAQ,mBAAmB,gBAAgB,iCAC3C,KAAK,4BACL,mBACC;;;qBCDU,2BAA2B;WACtB;WACA;EAEhB,YAAY,iBAAiB,qBAAkB;;qBAapC,4BAA4B;EACvC,YAAY,iBAAiB;;qBASlB,6BAA6B;EACxC,YAAY;;qBASD,4BAA4B;EACvC,YAAY;;;;iBCvCG;EACf,QAAQ;EAIR,oBAAoB;EAIpB;IACE,MAAM;;EAKR;EAKA;;wBAgBc,qBAAqB,SAAS;EA6H1C,QAAK,KAAQ,MAAI;EA4BjB,aAAK"}