alepha 0.22.0 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/jobs/index.d.ts +20 -20
- package/dist/api/jobs/index.d.ts.map +1 -1
- package/dist/api/keys/index.d.ts +6 -6
- package/dist/api/users/index.d.ts +43 -9
- package/dist/api/users/index.d.ts.map +1 -1
- package/dist/api/users/index.js +24 -3
- package/dist/api/users/index.js.map +1 -1
- package/dist/api/verifications/index.d.ts +13 -13
- package/dist/cli/core/index.d.ts +46 -40
- package/dist/cli/core/index.d.ts.map +1 -1
- package/dist/cli/core/index.js +51 -101
- package/dist/cli/core/index.js.map +1 -1
- package/dist/cli/i18n/index.d.ts +12 -5
- package/dist/cli/i18n/index.d.ts.map +1 -1
- package/dist/cli/i18n/index.js +45 -11
- package/dist/cli/i18n/index.js.map +1 -1
- package/dist/cli/platform-lib/index.d.ts +32 -6
- package/dist/cli/platform-lib/index.d.ts.map +1 -1
- package/dist/cli/platform-lib/index.js +82 -19
- package/dist/cli/platform-lib/index.js.map +1 -1
- package/dist/command/index.d.ts +1 -1
- package/dist/mcp/index.d.ts +9 -0
- package/dist/mcp/index.d.ts.map +1 -1
- package/dist/mcp/index.js +23 -0
- package/dist/mcp/index.js.map +1 -1
- package/dist/react/form/index.d.ts +0 -1
- package/dist/react/form/index.d.ts.map +1 -1
- package/dist/react/form/index.js +16 -15
- package/dist/react/form/index.js.map +1 -1
- package/dist/react/i18n/index.d.ts +43 -0
- package/dist/react/i18n/index.d.ts.map +1 -1
- package/dist/react/i18n/index.js +114 -10
- package/dist/react/i18n/index.js.map +1 -1
- package/dist/react/router/index.browser.js +128 -5
- package/dist/react/router/index.browser.js.map +1 -1
- package/dist/react/router/index.d.ts +108 -1
- package/dist/react/router/index.d.ts.map +1 -1
- package/dist/react/router/index.js +184 -6
- package/dist/react/router/index.js.map +1 -1
- package/dist/react/sitemap/index.browser.js +35 -0
- package/dist/react/sitemap/index.browser.js.map +1 -0
- package/dist/react/sitemap/index.d.ts +92 -0
- package/dist/react/sitemap/index.d.ts.map +1 -0
- package/dist/react/sitemap/index.js +131 -0
- package/dist/react/sitemap/index.js.map +1 -0
- package/dist/server/auth/index.d.ts +105 -1
- package/dist/server/auth/index.d.ts.map +1 -1
- package/dist/server/auth/index.js +1604 -7
- package/dist/server/auth/index.js.map +1 -1
- package/dist/server/cookies/index.d.ts +15 -0
- package/dist/server/cookies/index.d.ts.map +1 -1
- package/dist/server/cookies/index.js +22 -3
- package/dist/server/cookies/index.js.map +1 -1
- package/dist/server/core/index.d.ts +18 -0
- package/dist/server/core/index.d.ts.map +1 -1
- package/dist/server/core/index.js +25 -0
- package/dist/server/core/index.js.map +1 -1
- package/package.json +16 -3
- package/src/api/users/controllers/RealmController.ts +1 -0
- package/src/api/users/primitives/$realm.ts +26 -0
- package/src/api/users/providers/RealmProvider.ts +15 -0
- package/src/api/users/schemas/realmConfigSchema.ts +14 -0
- package/src/cli/core/atoms/buildOptions.ts +0 -12
- package/src/cli/core/commands/build.ts +0 -10
- package/src/cli/core/index.ts +0 -3
- package/src/cli/core/tasks/BuildCloudflareTask.ts +37 -17
- package/src/cli/core/tasks/BuildPrerenderTask.ts +44 -7
- package/src/cli/i18n/__tests__/I18nCheckService.spec.ts +48 -0
- package/src/cli/i18n/services/I18nCheckService.ts +65 -11
- package/src/cli/platform-lib/adapters/CloudflareAdapter.ts +128 -36
- package/src/mcp/__tests__/McpServerProvider.spec.ts +71 -0
- package/src/mcp/providers/McpServerProvider.ts +55 -0
- package/src/react/form/__tests__/FormModel-submit-loading.spec.ts +71 -0
- package/src/react/form/__tests__/form-submitting-reactive.browser.spec.tsx +96 -0
- package/src/react/form/services/FormModel.ts +57 -39
- package/src/react/i18n/__tests__/I18nProvider.spec.ts +89 -0
- package/src/react/i18n/__tests__/locale-routing.spec.ts +107 -0
- package/src/react/i18n/providers/I18nProvider.ts +171 -12
- package/src/react/router/__tests__/RouterLocaleProvider.spec.ts +127 -0
- package/src/react/router/index.browser.ts +4 -0
- package/src/react/router/index.shared.ts +1 -0
- package/src/react/router/index.ts +9 -0
- package/src/react/router/providers/ReactBrowserRouterProvider.ts +15 -1
- package/src/react/router/providers/ReactPageProvider.ts +12 -1
- package/src/react/router/providers/ReactServerProvider.ts +92 -1
- package/src/react/router/providers/RootComponentsProvider.ts +13 -0
- package/src/react/router/providers/RouterLocaleProvider.ts +125 -0
- package/src/react/router/providers/__tests__/RootComponentsProvider.spec.ts +15 -0
- package/src/react/router/providers/__tests__/rootComponents.ssr.browser.spec.tsx +67 -0
- package/src/react/sitemap/__tests__/$sitemap.spec.ts +131 -0
- package/src/react/sitemap/index.browser.ts +21 -0
- package/src/react/sitemap/index.ts +25 -0
- package/src/react/sitemap/primitives/$sitemap.browser.ts +26 -0
- package/src/react/sitemap/primitives/$sitemap.ts +196 -0
- package/src/server/auth/__tests__/appleClientSecret.spec.ts +34 -0
- package/src/server/auth/__tests__/authFederationClient.spec.ts +40 -0
- package/src/server/auth/__tests__/federationAssertion.spec.ts +146 -0
- package/src/server/auth/__tests__/federationRedirectReplay.spec.ts +44 -0
- package/src/server/auth/helpers/appleClientSecret.ts +24 -0
- package/src/server/auth/helpers/federationAssertion.ts +74 -0
- package/src/server/auth/helpers/jtiReplayGuard.ts +41 -0
- package/src/server/auth/helpers/safeRedirectPath.ts +19 -0
- package/src/server/auth/index.ts +4 -0
- package/src/server/auth/primitives/$authFederationBroker.ts +273 -0
- package/src/server/auth/primitives/$authFederationClient.ts +89 -0
- package/src/server/auth/providers/ServerAuthProvider.ts +18 -4
- package/src/server/cookies/__tests__/ServerCookiesProvider.spec.ts +70 -0
- package/src/server/cookies/providers/ServerCookiesProvider.ts +23 -3
- package/src/server/core/interfaces/ServerRequest.ts +8 -0
- package/src/server/core/primitives/$route.ts +27 -0
- package/src/cli/core/tasks/BuildSitemapTask.ts +0 -130
package/dist/command/index.d.ts
CHANGED
|
@@ -624,8 +624,8 @@ declare class CliProvider {
|
|
|
624
624
|
protected readonly asker: Asker;
|
|
625
625
|
protected readonly envUtils: EnvUtils;
|
|
626
626
|
protected readonly options: Readonly<{
|
|
627
|
-
name?: string | undefined;
|
|
628
627
|
description?: string | undefined;
|
|
628
|
+
name?: string | undefined;
|
|
629
629
|
argv?: string[] | undefined;
|
|
630
630
|
}>;
|
|
631
631
|
protected get name(): string;
|
package/dist/mcp/index.d.ts
CHANGED
|
@@ -712,6 +712,15 @@ declare class McpServerProvider {
|
|
|
712
712
|
tools: McpToolDescriptor[];
|
|
713
713
|
};
|
|
714
714
|
protected handleToolsCall(params: Record<string, unknown>, context?: McpContext): Promise<McpToolCallResult>;
|
|
715
|
+
/**
|
|
716
|
+
* Recognize a tool handler's return value as a pre-built MCP tool result —
|
|
717
|
+
* i.e. it already carries a `content` array of content blocks (text, image,
|
|
718
|
+
* audio, resource, resource_link). Returns the normalized
|
|
719
|
+
* {@link McpToolCallResult} when matched, or `undefined` to fall back to the
|
|
720
|
+
* default JSON/text encoding. Only ever consulted for tools that did NOT
|
|
721
|
+
* declare an output schema (see {@link handleToolCall}).
|
|
722
|
+
*/
|
|
723
|
+
protected asRawToolContent(result: unknown): McpToolCallResult | undefined;
|
|
715
724
|
protected handleResourcesList(): {
|
|
716
725
|
resources: McpResourceDescriptor[];
|
|
717
726
|
};
|
package/dist/mcp/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/mcp/errors/McpError.ts","../../src/mcp/interfaces/McpTypes.ts","../../src/mcp/helpers/jsonrpc.ts","../../src/mcp/primitives/$resource.ts","../../src/mcp/primitives/$tool.ts","../../src/mcp/providers/McpServerProvider.ts","../../src/mcp/primitives/$prompt.ts","../../src/mcp/transports/StreamableHttpMcpTransport.ts","../../src/mcp/index.ts"],"mappings":";;;;;;cAOa,aAAA;EAAA,SAGH,YAAA;EAAA,SAAA,SAAA;AAAA;AAAA,cAIG,QAAA,SAAiB,KAAK;EACjC,I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B,CAAA;EAAA,mBAEF,SAAA,EAAS,iBAAA;EHrIpB;;AAAY;EAAZ,IG0IG,IAAA;EHvIuB;;;EAAA,IG8IvB,WAAA;EH5IX;;;;AACe;EGoJR,eAAA;EAAA,UAIG,MAAA;;;;;;;AHlJN;EG6JS,OAAA,CACX,MAAA,WACA,OAAA,GAAU,UAAA,GACT,OAAA,CAAQ,iBAAA,CAAkB,CAAA;EHzJC;;;;;;;EG2LvB,YAAA,IAAgB,iBAAA;EH1Lf;;;;;;AAEQ;AAOlB;EATU,UGoOE,kBAAA,CACR,MAAA,EAAQ,OAAA,EACR,OAAA;IAAY,IAAA;EAAA,IACX,aAAA;EH7NH;;;EAAA,UG4PU,oBAAA,CAAqB,MAAA,EAAQ,OAAA,GAAU,MAAA;AAAA;;;;;;AJ7RnD;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/mcp/errors/McpError.ts","../../src/mcp/interfaces/McpTypes.ts","../../src/mcp/helpers/jsonrpc.ts","../../src/mcp/primitives/$resource.ts","../../src/mcp/primitives/$tool.ts","../../src/mcp/providers/McpServerProvider.ts","../../src/mcp/primitives/$prompt.ts","../../src/mcp/transports/StreamableHttpMcpTransport.ts","../../src/mcp/index.ts"],"mappings":";;;;;;cAOa,aAAA;EAAA,SAGH,YAAA;EAAA,SAAA,SAAA;AAAA;AAAA,cAIG,QAAA,SAAiB,KAAK;EACjC,IAAA;EACA,IAAA;cAGE,OAAA,UACA,IAAA;AAAA;AAAA,cASS,sBAAA,SAA+B,QAAQ;EAClD,IAAA;cAEY,MAAA;AAAA;AAAA,cAOD,oBAAA,SAA6B,QAAQ;EAChD,IAAA;EACA,IAAA;cAEY,IAAA;AAAA;AAAA,cAQD,wBAAA,SAAiC,QAAQ;EACpD,IAAA;EACA,GAAA;cAEY,GAAA;AAAA;AAAA,cAQD,sBAAA,SAA+B,QAAQ;EAClD,IAAA;EACA,MAAA;cAEY,MAAA;AAAA;AAAA,cAQD,qBAAA,SAA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UAID,MAAA;ELrID;;AAAM;AAGjB;;;;EK6Ie,GAAA,CACX,OAAA,WACA,OAAA,GAAU,UAAA,GACT,OAAA,CAAQ,aAAA;EL9IX;;;EK2JO,YAAA,IAAgB,mBAAA;ELzJH;AAAA;AAGtB;EAHsB,UK2KV,iBAAA,CAAkB,MAAA,EAAQ,OAAA,GAAU,iBAAA;AAAA;;;cC9KnC,wBAAA,mBAAwB,IAAA,mBAAA,OAAA;;APPrC;;;;;AAOA;;;;;;;;;;EAMmD;AAAA;AASnD;;;;;;;;;;EAUa;;;;;;;;cO4BA,aAAA,mBAAa,IAAA,mBAAA,OAAA;EPxBA;AAAA;AAQ1B;;;EAAsD;;;;;;;AAI7B;AAQzB;;;EAAoD;;;;;;;AAIxB;AAQ5B;;;;EAA2C;;;;;AAGd;;;;;;;;;;AAUS;AAOtC;;;;;;;;;AAGmC;;;;AC5FnC;;;;;;;;;;AAIiB;AAGjB;;;;;;;cMiGa,0BAAA;EAAA,mBACQ,GAAA,0BAAG,MAAA;EAAA,mBACH,OAAA,EAAO,QAAA;;;;;;qBACP,SAAA,EAAS,iBAAA;EN3F5B;;;;AACe;AAGjB;EM+FE,UAAA,0BAAU,cAAA,yBAAA,mBAAA;;;;;;;EAmBV,OAAA,0BAAO,cAAA;;;;;;;;;cAqII,eAAA,SAAe,0BAA6B;;;;;;;;;;;AP7PN;AASnD;;;cQmFa,SAAA,mBAAS,OAAA,kBAAA,MAAA"}
|
package/dist/mcp/index.js
CHANGED
|
@@ -354,6 +354,10 @@ var McpServerProvider = class {
|
|
|
354
354
|
if (!tool) throw new McpToolNotFoundError(name);
|
|
355
355
|
try {
|
|
356
356
|
const result = await tool.execute(args, context);
|
|
357
|
+
if (!tool.hasOutputSchema()) {
|
|
358
|
+
const raw = this.asRawToolContent(result);
|
|
359
|
+
if (raw) return raw;
|
|
360
|
+
}
|
|
357
361
|
const callResult = { content: [{
|
|
358
362
|
type: "text",
|
|
359
363
|
text: typeof result === "string" ? result : JSON.stringify(result ?? null)
|
|
@@ -385,6 +389,25 @@ var McpServerProvider = class {
|
|
|
385
389
|
};
|
|
386
390
|
}
|
|
387
391
|
}
|
|
392
|
+
/**
|
|
393
|
+
* Recognize a tool handler's return value as a pre-built MCP tool result —
|
|
394
|
+
* i.e. it already carries a `content` array of content blocks (text, image,
|
|
395
|
+
* audio, resource, resource_link). Returns the normalized
|
|
396
|
+
* {@link McpToolCallResult} when matched, or `undefined` to fall back to the
|
|
397
|
+
* default JSON/text encoding. Only ever consulted for tools that did NOT
|
|
398
|
+
* declare an output schema (see {@link handleToolCall}).
|
|
399
|
+
*/
|
|
400
|
+
asRawToolContent(result) {
|
|
401
|
+
if (!result || typeof result !== "object") return;
|
|
402
|
+
const candidate = result;
|
|
403
|
+
if (!Array.isArray(candidate.content) || candidate.content.length === 0) return;
|
|
404
|
+
if (!candidate.content.every((block) => !!block && typeof block === "object" && typeof block.type === "string")) return;
|
|
405
|
+
return {
|
|
406
|
+
content: candidate.content,
|
|
407
|
+
isError: typeof candidate.isError === "boolean" ? candidate.isError : void 0,
|
|
408
|
+
_meta: candidate._meta && typeof candidate._meta === "object" ? candidate._meta : void 0
|
|
409
|
+
};
|
|
410
|
+
}
|
|
388
411
|
handleResourcesList() {
|
|
389
412
|
return { resources: Array.from(this.resources.values()).map((r) => r.toDescriptor()) };
|
|
390
413
|
}
|
package/dist/mcp/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/mcp/helpers/jsonrpc.ts","../../src/mcp/errors/McpError.ts","../../src/mcp/providers/McpServerProvider.ts","../../src/mcp/primitives/$prompt.ts","../../src/mcp/primitives/$resource.ts","../../src/mcp/primitives/$tool.ts","../../src/mcp/transports/StreamableHttpMcpTransport.ts","../../src/mcp/index.ts"],"sourcesContent":["import { AlephaError } from \"alepha\";\nimport type {\n JsonRpcError,\n JsonRpcNotification,\n JsonRpcRequest,\n JsonRpcResponse,\n} from \"../interfaces/McpTypes.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport const JSONRPC_VERSION = \"2.0\" as const;\n\n/**\n * The latest MCP protocol revision Alepha targets.\n * See {@link SUPPORTED_PROTOCOL_VERSIONS} for the full negotiation list.\n */\nexport const MCP_PROTOCOL_VERSION = \"2025-11-25\" as const;\n\n/**\n * Protocol versions Alepha will accept during `initialize` negotiation,\n * highest preference first. The server echoes back whichever version the\n * client requested if it appears here, otherwise picks the first entry.\n */\nexport const SUPPORTED_PROTOCOL_VERSIONS = [\n \"2025-11-25\",\n \"2025-06-18\",\n \"2025-03-26\",\n \"2024-11-05\",\n] as const;\n\nexport type SupportedProtocolVersion =\n (typeof SUPPORTED_PROTOCOL_VERSIONS)[number];\n\nexport const isSupportedProtocolVersion = (\n v: unknown,\n): v is SupportedProtocolVersion =>\n typeof v === \"string\" &&\n (SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(v);\n\nexport const JsonRpcErrorCodes = {\n PARSE_ERROR: -32700,\n INVALID_REQUEST: -32600,\n METHOD_NOT_FOUND: -32601,\n INVALID_PARAMS: -32602,\n INTERNAL_ERROR: -32603,\n} as const;\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Response Builders\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport function createResponse(\n id: string | number,\n result: unknown,\n): JsonRpcResponse {\n return {\n jsonrpc: JSONRPC_VERSION,\n id,\n result,\n };\n}\n\nexport function createErrorResponse(\n id: string | number,\n error: JsonRpcError,\n): JsonRpcResponse {\n return {\n jsonrpc: JSONRPC_VERSION,\n id,\n error,\n };\n}\n\nexport function createNotification(\n method: string,\n params?: Record<string, unknown>,\n): JsonRpcNotification {\n return {\n jsonrpc: JSONRPC_VERSION,\n method,\n params,\n };\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Error Builders\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport function createParseError(message = \"Parse error\"): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.PARSE_ERROR,\n message,\n };\n}\n\nexport function createInvalidRequestError(\n message = \"Invalid request\",\n): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.INVALID_REQUEST,\n message,\n };\n}\n\nexport function createMethodNotFoundError(method: string): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.METHOD_NOT_FOUND,\n message: `Method not found: ${method}`,\n };\n}\n\nexport function createInvalidParamsError(message: string): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.INVALID_PARAMS,\n message,\n };\n}\n\nexport function createInternalError(message: string): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.INTERNAL_ERROR,\n message,\n };\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Message Parsing\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport function parseMessage(data: string): JsonRpcRequest {\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(data);\n } catch {\n throw new JsonRpcParseError(\"Invalid JSON\");\n }\n\n if (!isValidJsonRpcRequest(parsed)) {\n throw new JsonRpcParseError(\"Invalid JSON-RPC request\");\n }\n\n return parsed;\n}\n\nexport function isValidJsonRpcRequest(value: unknown): value is JsonRpcRequest {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const obj = value as Record<string, unknown>;\n\n if (obj.jsonrpc !== JSONRPC_VERSION) {\n return false;\n }\n\n if (typeof obj.method !== \"string\") {\n return false;\n }\n\n if (\n obj.id !== undefined &&\n typeof obj.id !== \"string\" &&\n typeof obj.id !== \"number\"\n ) {\n return false;\n }\n\n if (obj.params !== undefined && typeof obj.params !== \"object\") {\n return false;\n }\n\n return true;\n}\n\nexport function isNotification(request: JsonRpcRequest): boolean {\n return request.id === undefined;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class JsonRpcParseError extends AlephaError {\n name = \"JsonRpcParseError\";\n}\n","import { JsonRpcErrorCodes } from \"../helpers/jsonrpc.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * MCP-specific error codes (application-specific codes in the -32000 to -32099 range).\n */\nexport const McpErrorCodes = {\n UNAUTHORIZED: -32001,\n FORBIDDEN: -32003,\n} as const;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpError extends Error {\n name = \"McpError\";\n code: number;\n\n constructor(\n message: string,\n code: number = JsonRpcErrorCodes.INTERNAL_ERROR,\n ) {\n super(message);\n this.code = code;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpMethodNotFoundError extends McpError {\n name = \"McpMethodNotFoundError\";\n\n constructor(method: string) {\n super(`Method not found: ${method}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpToolNotFoundError extends McpError {\n name = \"McpToolNotFoundError\";\n tool: string;\n\n constructor(tool: string) {\n super(`Tool not found: ${tool}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n this.tool = tool;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpResourceNotFoundError extends McpError {\n name = \"McpResourceNotFoundError\";\n uri: string;\n\n constructor(uri: string) {\n super(`Resource not found: ${uri}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n this.uri = uri;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpPromptNotFoundError extends McpError {\n name = \"McpPromptNotFoundError\";\n prompt: string;\n\n constructor(prompt: string) {\n super(`Prompt not found: ${prompt}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n this.prompt = prompt;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpInvalidParamsError extends McpError {\n name = \"McpInvalidParamsError\";\n\n constructor(message: string) {\n super(message, JsonRpcErrorCodes.INVALID_PARAMS);\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpUnauthorizedError extends McpError {\n name = \"McpUnauthorizedError\";\n\n constructor(message = \"Unauthorized\") {\n super(message, McpErrorCodes.UNAUTHORIZED);\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpForbiddenError extends McpError {\n name = \"McpForbiddenError\";\n\n constructor(message = \"Forbidden\") {\n super(message, McpErrorCodes.FORBIDDEN);\n }\n}\n","import { $inject, Alepha, TypeBoxError } from \"alepha\";\nimport { $logger } from \"alepha/logger\";\nimport {\n McpError,\n McpMethodNotFoundError,\n McpPromptNotFoundError,\n McpResourceNotFoundError,\n McpToolNotFoundError,\n} from \"../errors/McpError.ts\";\nimport {\n createErrorResponse,\n createInternalError,\n createResponse,\n isSupportedProtocolVersion,\n MCP_PROTOCOL_VERSION,\n SUPPORTED_PROTOCOL_VERSIONS,\n} from \"../helpers/jsonrpc.ts\";\nimport type {\n JsonRpcRequest,\n JsonRpcResponse,\n McpCapabilities,\n McpContext,\n McpInitializeResult,\n McpPromptDescriptor,\n McpPromptGetResult,\n McpPromptMessage,\n McpResourceContent,\n McpResourceDescriptor,\n McpResourceReadResult,\n McpServerInfo,\n McpToolCallResult,\n McpToolDescriptor,\n} from \"../interfaces/McpTypes.ts\";\nimport type { PromptPrimitive } from \"../primitives/$prompt.ts\";\nimport type { ResourcePrimitive } from \"../primitives/$resource.ts\";\nimport type { ToolPrimitive } from \"../primitives/$tool.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Core MCP server provider that handles protocol messages.\n *\n * This provider maintains registries of tools, resources, and prompts,\n * and routes incoming JSON-RPC requests to the appropriate handlers.\n *\n * It is transport-agnostic - actual communication is handled by\n * transport providers like StdioMcpTransport or SseMcpTransport.\n */\nexport class McpServerProvider {\n protected readonly log = $logger();\n protected readonly alepha = $inject(Alepha);\n\n protected readonly tools = new Map<string, ToolPrimitive<any>>();\n protected readonly resources = new Map<string, ResourcePrimitive>();\n protected readonly prompts = new Map<string, PromptPrimitive<any>>();\n\n protected initialized = false;\n\n /**\n * Protocol version negotiated with the client during `initialize`.\n * Used by transports to validate the `MCP-Protocol-Version` header on\n * subsequent HTTP requests (per spec 2025-06-18+).\n */\n public negotiatedVersion: string = MCP_PROTOCOL_VERSION;\n\n /**\n * Server identity returned during `initialize`. Consumers may override\n * fields directly (e.g. `mcpServer.serverInfo = { name: \"lore-mcp\",\n * version: \"0.20.3\", description: \"...\" }`) — the `description` field\n * is supported per spec 2025-11-25 (minor change #2).\n */\n public serverInfo: McpServerInfo = {\n name: \"alepha-mcp\",\n version: \"1.0.0\",\n };\n\n // -----------------------------------------------------------------------------------------------------------------\n // Registration Methods\n // -----------------------------------------------------------------------------------------------------------------\n\n /**\n * Register a tool with the MCP server.\n */\n public registerTool(tool: ToolPrimitive<any>): void {\n this.log.trace(`Registering MCP tool: ${tool.name}`);\n this.tools.set(tool.name, tool);\n }\n\n /**\n * Register a resource with the MCP server.\n */\n public registerResource(resource: ResourcePrimitive): void {\n this.log.trace(`Registering MCP resource: ${resource.uri}`);\n this.resources.set(resource.uri, resource);\n }\n\n /**\n * Register a prompt with the MCP server.\n */\n public registerPrompt(prompt: PromptPrimitive<any>): void {\n this.log.trace(`Registering MCP prompt: ${prompt.name}`);\n this.prompts.set(prompt.name, prompt);\n }\n\n // -----------------------------------------------------------------------------------------------------------------\n // Getters\n // -----------------------------------------------------------------------------------------------------------------\n\n /**\n * Get the server capabilities based on registered primitives.\n */\n public getCapabilities(): McpCapabilities {\n return {\n tools: this.tools.size > 0 ? {} : undefined,\n resources: this.resources.size > 0 ? {} : undefined,\n prompts: this.prompts.size > 0 ? {} : undefined,\n };\n }\n\n /**\n * Get all registered tools.\n */\n public getTools(): ToolPrimitive<any>[] {\n return Array.from(this.tools.values());\n }\n\n /**\n * Get all registered resources.\n */\n public getResources(): ResourcePrimitive[] {\n return Array.from(this.resources.values());\n }\n\n /**\n * Get all registered prompts.\n */\n public getPrompts(): PromptPrimitive<any>[] {\n return Array.from(this.prompts.values());\n }\n\n /**\n * Get a tool by name.\n */\n public getTool(name: string): ToolPrimitive<any> | undefined {\n return this.tools.get(name);\n }\n\n /**\n * Get a resource by URI.\n */\n public getResource(uri: string): ResourcePrimitive | undefined {\n return this.resources.get(uri);\n }\n\n /**\n * Get a prompt by name.\n */\n public getPrompt(name: string): PromptPrimitive<any> | undefined {\n return this.prompts.get(name);\n }\n\n // -----------------------------------------------------------------------------------------------------------------\n // Message Handling\n // -----------------------------------------------------------------------------------------------------------------\n\n /**\n * Handle an incoming JSON-RPC request.\n *\n * @param request - The parsed JSON-RPC request\n * @param context - Optional context from the transport layer (headers, auth, etc.)\n * @returns The JSON-RPC response, or null for notifications\n */\n public async handleMessage(\n request: JsonRpcRequest,\n context?: McpContext,\n ): Promise<JsonRpcResponse | null> {\n const id = request.id;\n\n // Notifications have no id and expect no response\n if (id === undefined) {\n await this.handleNotification(request);\n return null;\n }\n\n try {\n const result = await this.handleRequest(request, context);\n return createResponse(id, result);\n } catch (error) {\n this.log.error(\"MCP request failed\", error);\n // Preserve error code from McpError instances\n if (error instanceof McpError) {\n return createErrorResponse(id, {\n code: error.code,\n message: error.message,\n });\n }\n return createErrorResponse(\n id,\n createInternalError((error as Error).message),\n );\n }\n }\n\n /**\n * Handle a JSON-RPC request that expects a response.\n */\n protected async handleRequest(\n request: JsonRpcRequest,\n context?: McpContext,\n ): Promise<unknown> {\n const { method, params = {} } = request;\n\n switch (method) {\n case \"initialize\":\n return this.handleInitialize(params);\n case \"ping\":\n return this.handlePing();\n case \"tools/list\":\n return this.handleToolsList();\n case \"tools/call\":\n return this.handleToolsCall(params, context);\n case \"resources/list\":\n return this.handleResourcesList();\n case \"resources/read\":\n return this.handleResourcesRead(params, context);\n case \"prompts/list\":\n return this.handlePromptsList();\n case \"prompts/get\":\n return this.handlePromptsGet(params, context);\n default:\n throw new McpMethodNotFoundError(method);\n }\n }\n\n /**\n * Handle a notification (no response expected).\n */\n protected async handleNotification(request: JsonRpcRequest): Promise<void> {\n const { method } = request;\n\n switch (method) {\n case \"notifications/initialized\":\n this.log.debug(\"MCP client initialized\");\n break;\n case \"notifications/cancelled\":\n this.log.debug(\"MCP request cancelled\", request.params);\n break;\n default:\n this.log.debug(`Unknown MCP notification: ${method}`);\n }\n }\n\n // -----------------------------------------------------------------------------------------------------------------\n // Protocol Handlers\n // -----------------------------------------------------------------------------------------------------------------\n\n protected handleInitialize(\n params: Record<string, unknown>,\n ): McpInitializeResult {\n const requested = params.protocolVersion;\n // Echo the client's version when supported, otherwise reply with our\n // preferred version (highest entry in SUPPORTED_PROTOCOL_VERSIONS).\n // The client can then decide to retry, downgrade, or disconnect.\n const negotiated = isSupportedProtocolVersion(requested)\n ? requested\n : SUPPORTED_PROTOCOL_VERSIONS[0];\n\n this.log.info(\"MCP client initializing\", {\n clientInfo: params.clientInfo,\n requestedProtocolVersion: requested,\n negotiatedProtocolVersion: negotiated,\n });\n\n this.initialized = true;\n this.negotiatedVersion = negotiated;\n\n return {\n protocolVersion: negotiated,\n capabilities: this.getCapabilities(),\n serverInfo: this.serverInfo,\n };\n }\n\n protected handlePing(): Record<string, never> {\n return {};\n }\n\n protected handleToolsList(): { tools: McpToolDescriptor[] } {\n return {\n tools: Array.from(this.tools.values()).map((t) => t.toDescriptor()),\n };\n }\n\n protected async handleToolsCall(\n params: Record<string, unknown>,\n context?: McpContext,\n ): Promise<McpToolCallResult> {\n const name = params.name as string;\n const args = (params.arguments ?? {}) as Record<string, unknown>;\n\n const tool = this.tools.get(name);\n if (!tool) {\n // McpToolNotFoundError is intentionally a JSON-RPC protocol error,\n // not a tool execution error — see SEP-1303 (only validation/runtime\n // failures of an existing tool are reported via isError: true).\n throw new McpToolNotFoundError(name);\n }\n\n try {\n const result = await tool.execute(args, context);\n\n const callResult: McpToolCallResult = {\n content: [\n {\n type: \"text\",\n text:\n typeof result === \"string\"\n ? result\n : JSON.stringify(result ?? null),\n },\n ],\n };\n\n // Spec 2025-06-18: when the tool declares an outputSchema, the server\n // MUST populate `structuredContent` with the validated result. The\n // text-stringified `content` block remains as a back-compat fallback.\n if (tool.hasOutputSchema() && result !== undefined) {\n callResult.structuredContent = result;\n }\n\n return callResult;\n } catch (error) {\n // Spec 2025-11-25 / SEP-1303: input-validation failures (and other\n // tool-runtime errors) are returned as Tool Execution Errors, not\n // JSON-RPC protocol errors, so the model can self-correct.\n // For TypeBox validation errors we surface the failing path so the\n // model knows which argument was malformed.\n if (error instanceof TypeBoxError) {\n const path = error.value?.path || \"/\";\n const message = error.value?.message || error.message;\n return {\n content: [\n {\n type: \"text\",\n text: `Validation error at ${path}: ${message}`,\n },\n ],\n structuredContent: {\n errors: [{ path, message }],\n },\n isError: true,\n };\n }\n\n return {\n content: [\n {\n type: \"text\",\n text: `Error: ${(error as Error).message}`,\n },\n ],\n isError: true,\n };\n }\n }\n\n protected handleResourcesList(): { resources: McpResourceDescriptor[] } {\n return {\n resources: Array.from(this.resources.values()).map((r) =>\n r.toDescriptor(),\n ),\n };\n }\n\n protected async handleResourcesRead(\n params: Record<string, unknown>,\n context?: McpContext,\n ): Promise<McpResourceReadResult> {\n const uri = params.uri as string;\n\n const resource = this.resources.get(uri);\n if (!resource) {\n throw new McpResourceNotFoundError(uri);\n }\n\n const content = await resource.read(context);\n\n const resourceContent: McpResourceContent = {\n uri,\n mimeType: resource.mimeType,\n };\n\n if (content.text !== undefined) {\n resourceContent.text = content.text;\n }\n\n if (content.blob !== undefined) {\n // Convert binary to base64 for transport\n resourceContent.blob = Buffer.from(content.blob).toString(\"base64\");\n }\n\n return {\n contents: [resourceContent],\n };\n }\n\n protected handlePromptsList(): { prompts: McpPromptDescriptor[] } {\n return {\n prompts: Array.from(this.prompts.values()).map((p) => p.toDescriptor()),\n };\n }\n\n protected async handlePromptsGet(\n params: Record<string, unknown>,\n context?: McpContext,\n ): Promise<McpPromptGetResult> {\n const name = params.name as string;\n const args = (params.arguments ?? {}) as Record<string, string>;\n\n const prompt = this.prompts.get(name);\n if (!prompt) {\n throw new McpPromptNotFoundError(name);\n }\n\n const messages = await prompt.get(args, context);\n\n const mcpMessages: McpPromptMessage[] = messages.map((msg) => ({\n role: msg.role,\n content: {\n type: \"text\" as const,\n text: msg.content,\n },\n }));\n\n return {\n description: prompt.description,\n messages: mcpMessages,\n };\n }\n}\n","import {\n $inject,\n type Async,\n createPrimitive,\n KIND,\n Primitive,\n type Static,\n type TObject,\n t,\n} from \"alepha\";\nimport type {\n McpContext,\n McpIcon,\n McpPromptArgument,\n McpPromptDescriptor,\n PromptHandlerArgs,\n PromptMessage,\n} from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Creates an MCP prompt primitive for defining reusable prompt templates.\n *\n * Prompts allow you to define templated messages that can be filled in\n * with arguments at runtime. They're useful for creating consistent\n * interaction patterns.\n *\n * @example\n * ```ts\n * class Prompts {\n * greeting = $prompt({\n * description: \"Generate a personalized greeting\",\n * args: t.object({\n * name: t.text({ description: \"Name of the person to greet\" }),\n * style: t.optional(t.enum([\"formal\", \"casual\"])),\n * }),\n * handler: async ({ args }) => [\n * {\n * role: \"user\",\n * content: args.style === \"formal\"\n * ? `Please greet ${args.name} in a formal manner.`\n * : `Say hi to ${args.name}!`,\n * },\n * ],\n * });\n *\n * codeReview = $prompt({\n * description: \"Request a code review\",\n * args: t.object({\n * code: t.text({ description: \"The code to review\" }),\n * language: t.text({ description: \"Programming language\" }),\n * }),\n * handler: async ({ args }) => [\n * {\n * role: \"user\",\n * content: `Please review this ${args.language} code:\\n\\n${args.code}`,\n * },\n * ],\n * });\n * }\n * ```\n */\nexport const $prompt = <T extends TObject>(\n options: PromptPrimitiveOptions<T>,\n): PromptPrimitive<T> => {\n return createPrimitive(PromptPrimitive<T>, options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface PromptPrimitiveOptions<T extends TObject> {\n /**\n * The name of the prompt.\n *\n * If not provided, defaults to the property key where the prompt is declared.\n *\n * @example \"greeting\"\n * @example \"code-review\"\n */\n name?: string;\n\n /**\n * Human-friendly display title (spec 2025-11-25). Distinct from `name`,\n * which remains the programmatic identifier.\n */\n title?: string;\n\n /**\n * Description of what this prompt does.\n *\n * Helps users understand the purpose of the prompt.\n *\n * @example \"Generate a personalized greeting message\"\n */\n description?: string;\n\n /**\n * Optional icons surfaced in client UIs (spec 2025-11-25 / SEP-973).\n */\n icons?: McpIcon[];\n\n /**\n * TypeBox schema defining the prompt arguments.\n *\n * Each property in the schema becomes an argument that can be\n * filled in when the prompt is used.\n */\n args?: T;\n\n /**\n * Handler function that generates the prompt messages.\n *\n * Receives the validated arguments and returns an array of messages.\n *\n * @param args - Object containing validated arguments\n * @returns Array of prompt messages\n */\n handler: (args: PromptHandlerArgs<T>) => Async<PromptMessage[]>;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class PromptPrimitive<T extends TObject> extends Primitive<\n PromptPrimitiveOptions<T>\n> {\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * Returns the name of the prompt.\n */\n public get name(): string {\n return this.options.name ?? this.config.propertyKey;\n }\n\n /**\n * Returns the description of the prompt.\n */\n public get description(): string | undefined {\n return this.options.description;\n }\n\n protected onInit(): void {\n this.mcpServer.registerPrompt(this);\n }\n\n /**\n * Get the prompt messages with the given arguments.\n *\n * @param rawArgs - Raw arguments to validate and pass to the handler\n * @param context - Optional context from the transport layer\n * @returns Array of prompt messages\n */\n public async get(\n rawArgs: unknown,\n context?: McpContext,\n ): Promise<PromptMessage[]> {\n let args = (rawArgs ?? {}) as Static<T>;\n\n if (this.options.args) {\n args = this.alepha.codec.decode(this.options.args, rawArgs ?? {});\n }\n\n return this.options.handler({ args, context });\n }\n\n /**\n * Convert the prompt to an MCP prompt descriptor for protocol messages.\n */\n public toDescriptor(): McpPromptDescriptor {\n const descriptor: McpPromptDescriptor = {\n name: this.name,\n description: this.description,\n arguments: this.options.args\n ? this.schemaToArguments(this.options.args)\n : [],\n };\n if (this.options.title) descriptor.title = this.options.title;\n if (this.options.icons && this.options.icons.length > 0) {\n descriptor.icons = this.options.icons;\n }\n return descriptor;\n }\n\n /**\n * Convert a TypeBox schema to an array of prompt arguments.\n */\n protected schemaToArguments(schema: TObject): McpPromptArgument[] {\n const args: McpPromptArgument[] = [];\n\n for (const [name, propSchema] of Object.entries(schema.properties)) {\n const prop = propSchema as Record<string, unknown>;\n args.push({\n name,\n description: prop.description as string | undefined,\n required: !t.schema.isOptional(propSchema),\n });\n }\n\n return args;\n }\n}\n\n$prompt[KIND] = PromptPrimitive;\n","import { $inject, createPrimitive, KIND, Primitive } from \"alepha\";\nimport type {\n McpContext,\n McpIcon,\n McpResourceDescriptor,\n ResourceContent,\n ResourceHandler,\n} from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Creates an MCP resource primitive for exposing read-only data.\n *\n * Resources represent any kind of data that an LLM might want to read,\n * such as files, database records, API responses, or computed data.\n *\n * **Key Features**\n * - URI-based identification for resources\n * - Support for text and binary content\n * - MIME type specification\n * - Lazy loading via handler function\n *\n * @example\n * ```ts\n * class ProjectResources {\n * readme = $resource({\n * uri: \"file:///readme\",\n * description: \"Project README file\",\n * mimeType: \"text/markdown\",\n * handler: async () => ({\n * text: await fs.readFile(\"README.md\", \"utf-8\"),\n * }),\n * });\n *\n * config = $resource({\n * uri: \"config://app\",\n * name: \"Application Configuration\",\n * mimeType: \"application/json\",\n * handler: async () => ({\n * text: JSON.stringify(this.configService.getConfig()),\n * }),\n * });\n * }\n * ```\n */\nexport const $resource = (\n options: ResourcePrimitiveOptions,\n): ResourcePrimitive => {\n return createPrimitive(ResourcePrimitive, options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface ResourcePrimitiveOptions {\n /**\n * The URI that identifies this resource.\n *\n * URIs should follow a consistent scheme for your application.\n * Common patterns:\n * - `file:///path/to/file` - File system resources\n * - `db://table/id` - Database records\n * - `api://endpoint` - API responses\n * - `config://name` - Configuration values\n *\n * @example \"file:///readme.md\"\n * @example \"db://users/123\"\n */\n uri: string;\n\n /**\n * Human-readable name for the resource.\n *\n * If not provided, defaults to the property key where the resource is declared.\n *\n * @example \"Project README\"\n * @example \"User Profile\"\n */\n name?: string;\n\n /**\n * Human-friendly display title (spec 2025-11-25). Distinct from `name`,\n * which remains the programmatic identifier.\n */\n title?: string;\n\n /**\n * Optional icons surfaced in client UIs (spec 2025-11-25 / SEP-973).\n */\n icons?: McpIcon[];\n\n /**\n * Description of what this resource contains.\n *\n * Helps the LLM understand the purpose and content of the resource.\n *\n * @example \"The main README file for the project\"\n */\n description?: string;\n\n /**\n * MIME type of the resource content.\n *\n * Helps clients understand how to interpret the content.\n *\n * @default \"text/plain\"\n * @example \"text/markdown\"\n * @example \"application/json\"\n */\n mimeType?: string;\n\n /**\n * Handler function that returns the resource content.\n *\n * Called when the resource is read. Can return text or binary content.\n *\n * @returns Resource content with either `text` or `blob` property\n */\n handler: ResourceHandler;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class ResourcePrimitive extends Primitive<ResourcePrimitiveOptions> {\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * Returns the name of the resource.\n */\n public get name(): string {\n return this.options.name ?? this.config.propertyKey;\n }\n\n /**\n * Returns the URI of the resource.\n */\n public get uri(): string {\n return this.options.uri;\n }\n\n /**\n * Returns the description of the resource.\n */\n public get description(): string | undefined {\n return this.options.description;\n }\n\n /**\n * Returns the MIME type of the resource.\n */\n public get mimeType(): string {\n return this.options.mimeType ?? \"text/plain\";\n }\n\n protected onInit(): void {\n this.mcpServer.registerResource(this);\n }\n\n /**\n * Read the resource content.\n *\n * @param context - Optional context from the transport layer\n * @returns The resource content\n */\n public async read(context?: McpContext): Promise<ResourceContent> {\n return this.options.handler({ context });\n }\n\n /**\n * Convert the resource to an MCP resource descriptor for protocol messages.\n */\n public toDescriptor(): McpResourceDescriptor {\n const descriptor: McpResourceDescriptor = {\n uri: this.uri,\n name: this.name,\n description: this.description,\n mimeType: this.mimeType,\n };\n if (this.options.title) descriptor.title = this.options.title;\n if (this.options.icons && this.options.icons.length > 0) {\n descriptor.icons = this.options.icons;\n }\n return descriptor;\n }\n}\n\n$resource[KIND] = ResourcePrimitive;\n","import {\n $inject,\n type Async,\n createPrimitive,\n KIND,\n Primitive,\n type TObject,\n type TSchema,\n t,\n} from \"alepha\";\nimport type {\n McpContext,\n McpIcon,\n McpJsonSchema,\n McpToolAnnotations,\n McpToolDescriptor,\n ToolHandlerArgs,\n ToolHandlerResult,\n ToolPrimitiveSchema,\n} from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Creates an MCP tool primitive for defining callable functions.\n *\n * Tools are the primary way for LLMs to interact with external systems through MCP.\n * Each tool has a name, description, typed parameters, and a handler function.\n *\n * **Key Features**\n * - Full TypeScript inference for parameters and results\n * - Automatic schema validation using TypeBox\n * - JSON Schema generation for MCP protocol\n * - Integration with MCP server provider\n *\n * @example\n * ```ts\n * class CalculatorTools {\n * add = $tool({\n * description: \"Add two numbers together\",\n * schema: {\n * params: t.object({\n * a: t.number(),\n * b: t.number(),\n * }),\n * result: t.number(),\n * },\n * handler: async ({ params }) => {\n * return params.a + params.b;\n * },\n * });\n *\n * greet = $tool({\n * description: \"Generate a greeting message\",\n * schema: {\n * params: t.object({\n * name: t.text(),\n * }),\n * result: t.text(),\n * },\n * handler: async ({ params }) => {\n * return `Hello, ${params.name}!`;\n * },\n * });\n * }\n * ```\n */\nexport const $tool = <T extends ToolPrimitiveSchema>(\n options: ToolPrimitiveOptions<T>,\n): ToolPrimitive<T> => {\n return createPrimitive(ToolPrimitive<T>, options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface ToolPrimitiveOptions<T extends ToolPrimitiveSchema> {\n /**\n * The name of the tool.\n *\n * If not provided, defaults to the property key where the tool is declared.\n * Names should be descriptive and use kebab-case or snake_case.\n *\n * @example \"calculate-sum\"\n * @example \"get_weather\"\n */\n name?: string;\n\n /**\n * Human-friendly display title (spec 2025-11-25). Distinct from `name`,\n * which remains the programmatic identifier. Clients use `title` in\n * tool palettes / picker UIs.\n *\n * @example \"Search Lore\"\n */\n title?: string;\n\n /**\n * A human-readable description of what the tool does.\n *\n * This description is sent to the LLM to help it understand\n * when and how to use the tool. Be clear and specific.\n *\n * @example \"Calculate the sum of two numbers\"\n * @example \"Retrieve current weather data for a given location\"\n */\n description: string;\n\n /**\n * Behavior hints (spec 2025-03-26+). Clients use these to gate UI prompts\n * (e.g. require confirmation before a tool with `destructiveHint: true`).\n * None are guarantees — they are heuristics for the client, not the model.\n */\n annotations?: McpToolAnnotations;\n\n /**\n * Icons surfaced in client tool palettes / picker UIs (spec 2025-11-25).\n */\n icons?: McpIcon[];\n\n /**\n * TypeBox schema defining the tool's parameters and result type.\n *\n * - **params**: TObject schema for input parameters (optional)\n * - **result**: TSchema for the return value (optional)\n *\n * Schemas provide:\n * - Type inference for handler function\n * - Runtime validation of inputs\n * - JSON Schema generation for MCP protocol\n */\n schema?: T;\n\n /**\n * The handler function that executes when the tool is called.\n *\n * Receives validated parameters and returns the result.\n * Errors thrown here are caught and returned as MCP errors.\n *\n * @param args - Object containing validated params\n * @returns The tool result (can be async)\n */\n handler: (args: ToolHandlerArgs<T>) => Async<ToolHandlerResult<T>>;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class ToolPrimitive<T extends ToolPrimitiveSchema> extends Primitive<\n ToolPrimitiveOptions<T>\n> {\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * Returns the name of the tool.\n */\n public get name(): string {\n return this.options.name ?? this.config.propertyKey;\n }\n\n /**\n * Returns the description of the tool.\n */\n public get description(): string {\n return this.options.description;\n }\n\n /**\n * Whether the tool declared a result schema. When true, `tools/call`\n * responses include `structuredContent` populated with the validated\n * result (spec 2025-06-18).\n */\n public hasOutputSchema(): boolean {\n return !!this.options.schema?.result;\n }\n\n protected onInit(): void {\n this.mcpServer.registerTool(this);\n }\n\n /**\n * Execute the tool with the given parameters.\n *\n * @param params - Raw parameters to validate and pass to the handler\n * @param context - Optional context from the transport layer\n * @returns The tool result\n */\n public async execute(\n params: unknown,\n context?: McpContext,\n ): Promise<ToolHandlerResult<T>> {\n let validatedParams: any = params ?? {};\n\n // Validate params using alepha.codec if schema provided\n if (this.options.schema?.params) {\n validatedParams = this.alepha.codec.decode(\n this.options.schema.params,\n validatedParams,\n );\n }\n\n const result = await this.options.handler({\n params: validatedParams,\n context,\n });\n\n // Validate and encode result if schema provided\n if (this.options.schema?.result && result !== undefined) {\n return this.alepha.codec.encode(\n this.options.schema.result,\n result,\n ) as ToolHandlerResult<T>;\n }\n\n return result as ToolHandlerResult<T>;\n }\n\n /**\n * Convert the tool to an MCP tool descriptor for protocol messages.\n *\n * Emits the spec 2025-11-25 surface: `title`, `annotations`, `icons`,\n * and (when `schema.result` is defined) `outputSchema` so the server\n * can populate `structuredContent` on call results.\n */\n public toDescriptor(): McpToolDescriptor {\n const inputSchema: McpJsonSchema = this.options.schema?.params\n ? this.schemaToJsonSchema(this.options.schema.params)\n : { type: \"object\", properties: {}, required: [] };\n\n const descriptor: McpToolDescriptor = {\n name: this.name,\n description: this.description,\n inputSchema,\n };\n\n if (this.options.title) descriptor.title = this.options.title;\n if (this.options.annotations)\n descriptor.annotations = this.options.annotations;\n if (this.options.icons && this.options.icons.length > 0) {\n descriptor.icons = this.options.icons;\n }\n\n // Output schema is emitted when the tool declares `schema.result`,\n // unlocking structured content on tools/call responses.\n if (this.options.schema?.result) {\n const out = this.propertyToJsonSchema(this.options.schema.result);\n // The result schema may be a primitive — wrap so the descriptor\n // value is always a JSON Schema object with `type`.\n descriptor.outputSchema = (\n typeof out === \"object\" && out !== null && \"type\" in out\n ? out\n : { type: \"object\", properties: {}, required: [] }\n ) as McpJsonSchema;\n }\n\n return descriptor;\n }\n\n /**\n * Convert a TypeBox schema to JSON Schema format.\n *\n * Emits the 2020-12 dialect annotation at the root (spec 2025-11-25 /\n * SEP-1613 — JSON Schema 2020-12 is the default dialect for MCP).\n * The TypeBox shapes Alepha emits today are already 2020-12-compatible;\n * this is just the dialect declaration.\n */\n protected schemaToJsonSchema(\n schema: TObject,\n options?: { root?: boolean },\n ): McpJsonSchema {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n properties[key] = this.propertyToJsonSchema(propSchema as TSchema);\n\n // Check if property is required (not optional)\n if (!t.schema.isOptional(propSchema as TSchema)) {\n required.push(key);\n }\n }\n\n const result: McpJsonSchema = {\n type: \"object\",\n properties,\n required,\n };\n\n // Annotate the dialect on the root schema only (avoid noise on nested\n // sub-schemas where MCP doesn't expect $schema).\n if (options?.root !== false) {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n\n return result;\n }\n\n /**\n * Convert a single property schema to JSON Schema format.\n */\n protected propertyToJsonSchema(schema: TSchema): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n // Check for description on all types\n if (\"description\" in schema) {\n result.description = schema.description;\n }\n\n if (t.schema.isString(schema)) {\n result.type = \"string\";\n if (\"minLength\" in schema) result.minLength = schema.minLength;\n if (\"maxLength\" in schema) result.maxLength = schema.maxLength;\n if (\"pattern\" in schema) result.pattern = schema.pattern;\n if (\"enum\" in schema) result.enum = schema.enum;\n } else if (t.schema.isNumber(schema)) {\n result.type = \"number\";\n if (\"minimum\" in schema) result.minimum = schema.minimum;\n if (\"maximum\" in schema) result.maximum = schema.maximum;\n } else if (t.schema.isInteger(schema)) {\n result.type = \"integer\";\n if (\"minimum\" in schema) result.minimum = schema.minimum;\n if (\"maximum\" in schema) result.maximum = schema.maximum;\n } else if (t.schema.isBoolean(schema)) {\n result.type = \"boolean\";\n } else if (t.schema.isArray(schema)) {\n result.type = \"array\";\n if (\"items\" in schema) {\n result.items = this.propertyToJsonSchema(schema.items as TSchema);\n }\n } else if (t.schema.isObject(schema)) {\n Object.assign(result, this.schemaToJsonSchema(schema, { root: false }));\n } else if (t.schema.isUnsafe(schema) || t.schema.isOptional(schema)) {\n // Handle Unsafe types (like t.enum) and optional wrappers by checking the underlying type property\n const schemaAny = schema as { type?: string; enum?: unknown[] };\n if (schemaAny.type === \"string\") {\n result.type = \"string\";\n if (\"enum\" in schema) result.enum = schema.enum;\n if (\"pattern\" in schema) result.pattern = schema.pattern;\n } else if (schemaAny.type === \"number\") {\n result.type = \"number\";\n } else if (schemaAny.type === \"integer\") {\n result.type = \"integer\";\n } else if (schemaAny.type === \"boolean\") {\n result.type = \"boolean\";\n } else if (schemaAny.type === \"array\") {\n result.type = \"array\";\n } else if (schemaAny.type === \"object\") {\n result.type = \"object\";\n } else {\n // Fallback\n result.type = \"string\";\n }\n } else {\n // Fallback for other types\n result.type = \"string\";\n }\n\n return result;\n }\n}\n\n$tool[KIND] = ToolPrimitive;\n","import { $atom, $inject, $state, t } from \"alepha\";\nimport { $logger } from \"alepha/logger\";\nimport { $route } from \"alepha/server\";\nimport {\n createErrorResponse,\n createParseError,\n JsonRpcParseError,\n parseMessage,\n} from \"../helpers/jsonrpc.ts\";\nimport type { McpContext } from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport const mcpStreamableHttpOptions = $atom({\n name: \"alepha.mcp.streamableHttp.options\",\n description: \"Configuration options for the MCP Streamable HTTP transport.\",\n schema: t.object({\n /**\n * Path for the MCP endpoint. Single endpoint for both requests and\n * (optional) server-streamed responses, per spec 2025-03-26+.\n */\n path: t.text({ default: \"/mcp\" }),\n /**\n * Allow-list of `Origin` header values accepted on incoming requests.\n * Empty array (default) means \"allow any\". When set, browser-originated\n * requests with a non-matching `Origin` are rejected with 403 Forbidden,\n * blocking DNS-rebinding attacks against localhost MCP servers.\n *\n * Server-to-server callers (no `Origin` header) are always allowed.\n *\n * Spec 2025-11-25, PR #1439.\n */\n allowedOrigins: t.array(t.text(), { default: [] }),\n /**\n * When true, an unauthenticated POST to the MCP endpoint is rejected\n * with `401 Unauthorized` and an RFC 9728 `WWW-Authenticate` challenge\n * instead of being dispatched. MCP clients (Claude, etc.) rely on that\n * challenge to discover the OAuth authorization server.\n *\n * The transport stays OAuth-agnostic: it only knows \"auth is required\".\n * `$realm({ features: { oauth: true } })` flips this on automatically.\n *\n * @default false\n */\n requireAuth: t.boolean({ default: false }),\n /**\n * Path of the RFC 9728 protected-resource metadata document, advertised\n * (as an absolute URL, resolved against the request origin) in the\n * `WWW-Authenticate` challenge emitted when {@link requireAuth} rejects\n * a request.\n */\n resourceMetadataPath: t.text({\n default: \"/.well-known/oauth-protected-resource\",\n }),\n }),\n default: {\n path: \"/mcp\",\n allowedOrigins: [],\n requireAuth: false,\n resourceMetadataPath: \"/.well-known/oauth-protected-resource\",\n },\n});\n\n// Backward-compat alias for the legacy atom name. Prefer\n// `mcpStreamableHttpOptions` going forward; this re-export keeps existing\n// consumer imports compiling and will be removed once they migrate.\nexport const mcpSseOptions = mcpStreamableHttpOptions;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Streamable HTTP transport for MCP communication.\n *\n * Implements the 2025-03-26+ Streamable HTTP transport: a single `/mcp`\n * endpoint that accepts JSON-RPC over POST and returns either\n * `application/json` (single response, the default) or\n * `text/event-stream` (when the server wants to stream multiple messages).\n *\n * Designed for serverless deployment (Cloudflare Workers, etc.) — there is\n * no long-lived GET stream. GET on the endpoint returns 405 Method Not\n * Allowed; clients that want server-initiated push must rely on the POST\n * response stream when the server upgrades to SSE for that particular call.\n *\n * Spec compliance:\n * - 2025-06-18: validates `MCP-Protocol-Version` header on every request\n * after `initialize` against the version negotiated and stored on\n * `McpServerProvider`.\n * - 2025-11-25: rejects requests with a non-allow-listed `Origin` header\n * (PR #1439). See {@link mcpStreamableHttpOptions.allowedOrigins}.\n *\n * @example\n * ```ts\n * import { Alepha, run } from \"alepha\";\n * import { AlephaServer } from \"alepha/server\";\n * import { AlephaMcp, StreamableHttpMcpTransport } from \"alepha/mcp\";\n *\n * class MyTools {\n * // ... tool definitions\n * }\n *\n * run(\n * Alepha.create()\n * .with(AlephaServer)\n * .with(AlephaMcp)\n * .with(StreamableHttpMcpTransport)\n * .with(MyTools)\n * );\n * ```\n */\nexport class StreamableHttpMcpTransport {\n protected readonly log = $logger();\n protected readonly options = $state(mcpStreamableHttpOptions);\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * GET on the MCP endpoint is not supported in this transport. Returning\n * 405 (rather than serving the legacy two-endpoint SSE pattern) is the\n * spec-allowed response for servers that don't offer server-initiated\n * push outside of an active POST.\n */\n notAllowed = $route({\n method: \"GET\",\n path: this.options.path,\n handler: (request) => {\n request.reply.status = 405;\n request.reply.headers.allow = \"POST\";\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify({\n error: \"Method Not Allowed. Use POST for MCP messages.\",\n });\n },\n });\n\n /**\n * POST endpoint for client-to-server JSON-RPC messages.\n * Returns `application/json` for single responses; tools that need to\n * stream progress would upgrade to `text/event-stream` (deferred until a\n * concrete need exists).\n */\n message = $route({\n method: \"POST\",\n path: this.options.path,\n schema: {\n body: t.json(),\n },\n handler: async (request) => {\n try {\n // Origin allow-list check (spec 2025-11-25 / PR #1439).\n const originRaw = request.headers.origin;\n const origin = Array.isArray(originRaw) ? originRaw[0] : originRaw;\n if (\n origin &&\n this.options.allowedOrigins.length > 0 &&\n !this.options.allowedOrigins.includes(origin)\n ) {\n this.log.warn(\"Rejected MCP request with non-allowed Origin\", {\n origin,\n allowed: this.options.allowedOrigins,\n });\n request.reply.status = 403;\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify({\n error: \"Forbidden: Origin not allowed\",\n });\n return;\n }\n\n // RFC 9728 / MCP auth (spec 2025-06-18+): when the endpoint is\n // OAuth-protected, an unauthenticated request is rejected with 401\n // and a `WWW-Authenticate` challenge pointing at the protected-\n // resource metadata. MCP clients (Claude, etc.) follow that\n // `resource_metadata` URL to discover the authorization server —\n // without it, discovery never starts. The URL MUST be absolute.\n if (this.options.requireAuth && !request.user) {\n const url =\n typeof request.url === \"string\"\n ? new URL(request.url)\n : request.url;\n const resourceMetadataUrl = `${url.protocol}//${url.host}${this.options.resourceMetadataPath}`;\n this.log.debug(\"Rejecting unauthenticated MCP request\", {\n resourceMetadataUrl,\n });\n request.reply.status = 401;\n request.reply.headers[\"www-authenticate\"] =\n `Bearer resource_metadata=\"${resourceMetadataUrl}\"`;\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify({\n error: \"Unauthorized\",\n });\n return;\n }\n\n const body =\n typeof request.body === \"string\"\n ? request.body\n : JSON.stringify(request.body);\n\n this.log.debug(\"MCP request body\", {\n body,\n bodyType: typeof request.body,\n });\n\n const rpcRequest = parseMessage(body);\n\n // Build context from request headers\n const headers = { ...request.headers } as Record<\n string,\n string | string[] | undefined\n >;\n\n // Spec 2025-06-18+: every HTTP request after `initialize` MUST carry\n // an `MCP-Protocol-Version` header matching the negotiated version.\n // Reject mismatches with 400 so the client doesn't silently drift.\n if (rpcRequest.method !== \"initialize\") {\n const headerRaw = headers[\"mcp-protocol-version\"];\n const headerVersion = Array.isArray(headerRaw)\n ? headerRaw[0]\n : headerRaw;\n if (\n headerVersion &&\n headerVersion !== this.mcpServer.negotiatedVersion\n ) {\n this.log.warn(\"MCP-Protocol-Version header mismatch\", {\n header: headerVersion,\n negotiated: this.mcpServer.negotiatedVersion,\n });\n request.reply.status = 400;\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify({\n error: `MCP-Protocol-Version mismatch: expected ${this.mcpServer.negotiatedVersion}, got ${headerVersion}`,\n });\n return;\n }\n }\n\n const context: McpContext = { headers };\n\n const response = await this.mcpServer.handleMessage(\n rpcRequest,\n context,\n );\n\n if (response) {\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify(response);\n } else {\n request.reply.status = 204;\n }\n } catch (error) {\n if (error instanceof JsonRpcParseError) {\n request.reply.status = 400;\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify(\n createErrorResponse(0, createParseError(error.message)),\n );\n } else {\n this.log.error(\"Failed to process MCP message\", error);\n request.reply.status = 500;\n request.reply.body = JSON.stringify({\n error: (error as Error).message,\n });\n }\n }\n },\n });\n}\n\n/**\n * @deprecated Use {@link StreamableHttpMcpTransport}. The 2024-11-05\n * two-endpoint HTTP+SSE pattern was replaced by Streamable HTTP in spec\n * 2025-03-26. This alias is preserved for one release to ease migration.\n */\nexport const SseMcpTransport = StreamableHttpMcpTransport;\n","import { $module } from \"alepha\";\nimport { $prompt } from \"./primitives/$prompt.ts\";\nimport { $resource } from \"./primitives/$resource.ts\";\nimport { $tool } from \"./primitives/$tool.ts\";\nimport { McpServerProvider } from \"./providers/McpServerProvider.ts\";\nimport { StreamableHttpMcpTransport } from \"./transports/StreamableHttpMcpTransport.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport {\n McpError,\n McpErrorCodes,\n McpForbiddenError,\n McpInvalidParamsError,\n McpMethodNotFoundError,\n McpPromptNotFoundError,\n McpResourceNotFoundError,\n McpToolNotFoundError,\n McpUnauthorizedError,\n} from \"./errors/McpError.ts\";\nexport {\n createErrorResponse,\n createInternalError,\n createInvalidParamsError,\n createInvalidRequestError,\n createMethodNotFoundError,\n createNotification,\n createParseError,\n createResponse,\n isNotification,\n isSupportedProtocolVersion,\n isValidJsonRpcRequest,\n JSONRPC_VERSION,\n JsonRpcErrorCodes,\n JsonRpcParseError,\n MCP_PROTOCOL_VERSION,\n parseMessage,\n SUPPORTED_PROTOCOL_VERSIONS,\n type SupportedProtocolVersion,\n} from \"./helpers/jsonrpc.ts\";\nexport type {\n JsonRpcError,\n JsonRpcNotification,\n // JSON-RPC types\n JsonRpcRequest,\n JsonRpcResponse,\n // MCP protocol types\n McpCapabilities,\n McpClientInfo,\n McpContent,\n // Context type for auth/headers\n McpContext,\n McpInitializeParams,\n McpInitializeResult,\n McpJsonSchema,\n McpPromptArgument,\n McpPromptContent,\n // Prompt types\n McpPromptDescriptor,\n McpPromptGetParams,\n McpPromptGetResult,\n McpPromptMessage,\n McpResourceContent,\n // Resource types\n McpResourceDescriptor,\n McpResourceReadParams,\n McpResourceReadResult,\n McpServerInfo,\n McpToolCallParams,\n McpToolCallResult,\n // Tool types\n McpToolDescriptor,\n PromptHandler,\n PromptHandlerArgs,\n PromptMessage,\n ResourceContent,\n ResourceHandler,\n ResourceHandlerArgs,\n ToolHandler,\n ToolHandlerArgs,\n ToolHandlerResult,\n // Handler types\n ToolPrimitiveSchema,\n} from \"./interfaces/McpTypes.ts\";\nexport type { PromptPrimitiveOptions } from \"./primitives/$prompt.ts\";\nexport { $prompt, PromptPrimitive } from \"./primitives/$prompt.ts\";\nexport type { ResourcePrimitiveOptions } from \"./primitives/$resource.ts\";\nexport { $resource, ResourcePrimitive } from \"./primitives/$resource.ts\";\nexport type { ToolPrimitiveOptions } from \"./primitives/$tool.ts\";\nexport { $tool, ToolPrimitive } from \"./primitives/$tool.ts\";\nexport { McpServerProvider } from \"./providers/McpServerProvider.ts\";\nexport {\n mcpSseOptions,\n mcpStreamableHttpOptions,\n SseMcpTransport,\n StreamableHttpMcpTransport,\n} from \"./transports/StreamableHttpMcpTransport.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Model Context Protocol for AI tool integration.\n *\n * **Features:**\n * - MCP resource definitions\n * - MCP tool definitions\n * - MCP prompt definitions\n * - JSON-RPC protocol\n * - Streamable HTTP transport (spec 2025-03-26+)\n *\n * @module alepha.mcp\n */\nexport const AlephaMcp = $module({\n name: \"alepha.mcp\",\n primitives: [$tool, $resource, $prompt],\n services: [McpServerProvider],\n // Transports are opt-in — user wires the one(s) they need via alepha.with(StreamableHttpMcpTransport).\n variants: [StreamableHttpMcpTransport],\n});\n"],"mappings":";;;;AAYA,MAAa,kBAAkB;;;;;AAM/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":["../../src/mcp/helpers/jsonrpc.ts","../../src/mcp/errors/McpError.ts","../../src/mcp/providers/McpServerProvider.ts","../../src/mcp/primitives/$prompt.ts","../../src/mcp/primitives/$resource.ts","../../src/mcp/primitives/$tool.ts","../../src/mcp/transports/StreamableHttpMcpTransport.ts","../../src/mcp/index.ts"],"sourcesContent":["import { AlephaError } from \"alepha\";\nimport type {\n JsonRpcError,\n JsonRpcNotification,\n JsonRpcRequest,\n JsonRpcResponse,\n} from \"../interfaces/McpTypes.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport const JSONRPC_VERSION = \"2.0\" as const;\n\n/**\n * The latest MCP protocol revision Alepha targets.\n * See {@link SUPPORTED_PROTOCOL_VERSIONS} for the full negotiation list.\n */\nexport const MCP_PROTOCOL_VERSION = \"2025-11-25\" as const;\n\n/**\n * Protocol versions Alepha will accept during `initialize` negotiation,\n * highest preference first. The server echoes back whichever version the\n * client requested if it appears here, otherwise picks the first entry.\n */\nexport const SUPPORTED_PROTOCOL_VERSIONS = [\n \"2025-11-25\",\n \"2025-06-18\",\n \"2025-03-26\",\n \"2024-11-05\",\n] as const;\n\nexport type SupportedProtocolVersion =\n (typeof SUPPORTED_PROTOCOL_VERSIONS)[number];\n\nexport const isSupportedProtocolVersion = (\n v: unknown,\n): v is SupportedProtocolVersion =>\n typeof v === \"string\" &&\n (SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(v);\n\nexport const JsonRpcErrorCodes = {\n PARSE_ERROR: -32700,\n INVALID_REQUEST: -32600,\n METHOD_NOT_FOUND: -32601,\n INVALID_PARAMS: -32602,\n INTERNAL_ERROR: -32603,\n} as const;\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Response Builders\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport function createResponse(\n id: string | number,\n result: unknown,\n): JsonRpcResponse {\n return {\n jsonrpc: JSONRPC_VERSION,\n id,\n result,\n };\n}\n\nexport function createErrorResponse(\n id: string | number,\n error: JsonRpcError,\n): JsonRpcResponse {\n return {\n jsonrpc: JSONRPC_VERSION,\n id,\n error,\n };\n}\n\nexport function createNotification(\n method: string,\n params?: Record<string, unknown>,\n): JsonRpcNotification {\n return {\n jsonrpc: JSONRPC_VERSION,\n method,\n params,\n };\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Error Builders\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport function createParseError(message = \"Parse error\"): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.PARSE_ERROR,\n message,\n };\n}\n\nexport function createInvalidRequestError(\n message = \"Invalid request\",\n): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.INVALID_REQUEST,\n message,\n };\n}\n\nexport function createMethodNotFoundError(method: string): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.METHOD_NOT_FOUND,\n message: `Method not found: ${method}`,\n };\n}\n\nexport function createInvalidParamsError(message: string): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.INVALID_PARAMS,\n message,\n };\n}\n\nexport function createInternalError(message: string): JsonRpcError {\n return {\n code: JsonRpcErrorCodes.INTERNAL_ERROR,\n message,\n };\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Message Parsing\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport function parseMessage(data: string): JsonRpcRequest {\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(data);\n } catch {\n throw new JsonRpcParseError(\"Invalid JSON\");\n }\n\n if (!isValidJsonRpcRequest(parsed)) {\n throw new JsonRpcParseError(\"Invalid JSON-RPC request\");\n }\n\n return parsed;\n}\n\nexport function isValidJsonRpcRequest(value: unknown): value is JsonRpcRequest {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const obj = value as Record<string, unknown>;\n\n if (obj.jsonrpc !== JSONRPC_VERSION) {\n return false;\n }\n\n if (typeof obj.method !== \"string\") {\n return false;\n }\n\n if (\n obj.id !== undefined &&\n typeof obj.id !== \"string\" &&\n typeof obj.id !== \"number\"\n ) {\n return false;\n }\n\n if (obj.params !== undefined && typeof obj.params !== \"object\") {\n return false;\n }\n\n return true;\n}\n\nexport function isNotification(request: JsonRpcRequest): boolean {\n return request.id === undefined;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class JsonRpcParseError extends AlephaError {\n name = \"JsonRpcParseError\";\n}\n","import { JsonRpcErrorCodes } from \"../helpers/jsonrpc.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * MCP-specific error codes (application-specific codes in the -32000 to -32099 range).\n */\nexport const McpErrorCodes = {\n UNAUTHORIZED: -32001,\n FORBIDDEN: -32003,\n} as const;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpError extends Error {\n name = \"McpError\";\n code: number;\n\n constructor(\n message: string,\n code: number = JsonRpcErrorCodes.INTERNAL_ERROR,\n ) {\n super(message);\n this.code = code;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpMethodNotFoundError extends McpError {\n name = \"McpMethodNotFoundError\";\n\n constructor(method: string) {\n super(`Method not found: ${method}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpToolNotFoundError extends McpError {\n name = \"McpToolNotFoundError\";\n tool: string;\n\n constructor(tool: string) {\n super(`Tool not found: ${tool}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n this.tool = tool;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpResourceNotFoundError extends McpError {\n name = \"McpResourceNotFoundError\";\n uri: string;\n\n constructor(uri: string) {\n super(`Resource not found: ${uri}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n this.uri = uri;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpPromptNotFoundError extends McpError {\n name = \"McpPromptNotFoundError\";\n prompt: string;\n\n constructor(prompt: string) {\n super(`Prompt not found: ${prompt}`, JsonRpcErrorCodes.METHOD_NOT_FOUND);\n this.prompt = prompt;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpInvalidParamsError extends McpError {\n name = \"McpInvalidParamsError\";\n\n constructor(message: string) {\n super(message, JsonRpcErrorCodes.INVALID_PARAMS);\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpUnauthorizedError extends McpError {\n name = \"McpUnauthorizedError\";\n\n constructor(message = \"Unauthorized\") {\n super(message, McpErrorCodes.UNAUTHORIZED);\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class McpForbiddenError extends McpError {\n name = \"McpForbiddenError\";\n\n constructor(message = \"Forbidden\") {\n super(message, McpErrorCodes.FORBIDDEN);\n }\n}\n","import { $inject, Alepha, TypeBoxError } from \"alepha\";\nimport { $logger } from \"alepha/logger\";\nimport {\n McpError,\n McpMethodNotFoundError,\n McpPromptNotFoundError,\n McpResourceNotFoundError,\n McpToolNotFoundError,\n} from \"../errors/McpError.ts\";\nimport {\n createErrorResponse,\n createInternalError,\n createResponse,\n isSupportedProtocolVersion,\n MCP_PROTOCOL_VERSION,\n SUPPORTED_PROTOCOL_VERSIONS,\n} from \"../helpers/jsonrpc.ts\";\nimport type {\n JsonRpcRequest,\n JsonRpcResponse,\n McpCapabilities,\n McpContent,\n McpContext,\n McpInitializeResult,\n McpPromptDescriptor,\n McpPromptGetResult,\n McpPromptMessage,\n McpResourceContent,\n McpResourceDescriptor,\n McpResourceReadResult,\n McpServerInfo,\n McpToolCallResult,\n McpToolDescriptor,\n} from \"../interfaces/McpTypes.ts\";\nimport type { PromptPrimitive } from \"../primitives/$prompt.ts\";\nimport type { ResourcePrimitive } from \"../primitives/$resource.ts\";\nimport type { ToolPrimitive } from \"../primitives/$tool.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Core MCP server provider that handles protocol messages.\n *\n * This provider maintains registries of tools, resources, and prompts,\n * and routes incoming JSON-RPC requests to the appropriate handlers.\n *\n * It is transport-agnostic - actual communication is handled by\n * transport providers like StdioMcpTransport or SseMcpTransport.\n */\nexport class McpServerProvider {\n protected readonly log = $logger();\n protected readonly alepha = $inject(Alepha);\n\n protected readonly tools = new Map<string, ToolPrimitive<any>>();\n protected readonly resources = new Map<string, ResourcePrimitive>();\n protected readonly prompts = new Map<string, PromptPrimitive<any>>();\n\n protected initialized = false;\n\n /**\n * Protocol version negotiated with the client during `initialize`.\n * Used by transports to validate the `MCP-Protocol-Version` header on\n * subsequent HTTP requests (per spec 2025-06-18+).\n */\n public negotiatedVersion: string = MCP_PROTOCOL_VERSION;\n\n /**\n * Server identity returned during `initialize`. Consumers may override\n * fields directly (e.g. `mcpServer.serverInfo = { name: \"lore-mcp\",\n * version: \"0.20.3\", description: \"...\" }`) — the `description` field\n * is supported per spec 2025-11-25 (minor change #2).\n */\n public serverInfo: McpServerInfo = {\n name: \"alepha-mcp\",\n version: \"1.0.0\",\n };\n\n // -----------------------------------------------------------------------------------------------------------------\n // Registration Methods\n // -----------------------------------------------------------------------------------------------------------------\n\n /**\n * Register a tool with the MCP server.\n */\n public registerTool(tool: ToolPrimitive<any>): void {\n this.log.trace(`Registering MCP tool: ${tool.name}`);\n this.tools.set(tool.name, tool);\n }\n\n /**\n * Register a resource with the MCP server.\n */\n public registerResource(resource: ResourcePrimitive): void {\n this.log.trace(`Registering MCP resource: ${resource.uri}`);\n this.resources.set(resource.uri, resource);\n }\n\n /**\n * Register a prompt with the MCP server.\n */\n public registerPrompt(prompt: PromptPrimitive<any>): void {\n this.log.trace(`Registering MCP prompt: ${prompt.name}`);\n this.prompts.set(prompt.name, prompt);\n }\n\n // -----------------------------------------------------------------------------------------------------------------\n // Getters\n // -----------------------------------------------------------------------------------------------------------------\n\n /**\n * Get the server capabilities based on registered primitives.\n */\n public getCapabilities(): McpCapabilities {\n return {\n tools: this.tools.size > 0 ? {} : undefined,\n resources: this.resources.size > 0 ? {} : undefined,\n prompts: this.prompts.size > 0 ? {} : undefined,\n };\n }\n\n /**\n * Get all registered tools.\n */\n public getTools(): ToolPrimitive<any>[] {\n return Array.from(this.tools.values());\n }\n\n /**\n * Get all registered resources.\n */\n public getResources(): ResourcePrimitive[] {\n return Array.from(this.resources.values());\n }\n\n /**\n * Get all registered prompts.\n */\n public getPrompts(): PromptPrimitive<any>[] {\n return Array.from(this.prompts.values());\n }\n\n /**\n * Get a tool by name.\n */\n public getTool(name: string): ToolPrimitive<any> | undefined {\n return this.tools.get(name);\n }\n\n /**\n * Get a resource by URI.\n */\n public getResource(uri: string): ResourcePrimitive | undefined {\n return this.resources.get(uri);\n }\n\n /**\n * Get a prompt by name.\n */\n public getPrompt(name: string): PromptPrimitive<any> | undefined {\n return this.prompts.get(name);\n }\n\n // -----------------------------------------------------------------------------------------------------------------\n // Message Handling\n // -----------------------------------------------------------------------------------------------------------------\n\n /**\n * Handle an incoming JSON-RPC request.\n *\n * @param request - The parsed JSON-RPC request\n * @param context - Optional context from the transport layer (headers, auth, etc.)\n * @returns The JSON-RPC response, or null for notifications\n */\n public async handleMessage(\n request: JsonRpcRequest,\n context?: McpContext,\n ): Promise<JsonRpcResponse | null> {\n const id = request.id;\n\n // Notifications have no id and expect no response\n if (id === undefined) {\n await this.handleNotification(request);\n return null;\n }\n\n try {\n const result = await this.handleRequest(request, context);\n return createResponse(id, result);\n } catch (error) {\n this.log.error(\"MCP request failed\", error);\n // Preserve error code from McpError instances\n if (error instanceof McpError) {\n return createErrorResponse(id, {\n code: error.code,\n message: error.message,\n });\n }\n return createErrorResponse(\n id,\n createInternalError((error as Error).message),\n );\n }\n }\n\n /**\n * Handle a JSON-RPC request that expects a response.\n */\n protected async handleRequest(\n request: JsonRpcRequest,\n context?: McpContext,\n ): Promise<unknown> {\n const { method, params = {} } = request;\n\n switch (method) {\n case \"initialize\":\n return this.handleInitialize(params);\n case \"ping\":\n return this.handlePing();\n case \"tools/list\":\n return this.handleToolsList();\n case \"tools/call\":\n return this.handleToolsCall(params, context);\n case \"resources/list\":\n return this.handleResourcesList();\n case \"resources/read\":\n return this.handleResourcesRead(params, context);\n case \"prompts/list\":\n return this.handlePromptsList();\n case \"prompts/get\":\n return this.handlePromptsGet(params, context);\n default:\n throw new McpMethodNotFoundError(method);\n }\n }\n\n /**\n * Handle a notification (no response expected).\n */\n protected async handleNotification(request: JsonRpcRequest): Promise<void> {\n const { method } = request;\n\n switch (method) {\n case \"notifications/initialized\":\n this.log.debug(\"MCP client initialized\");\n break;\n case \"notifications/cancelled\":\n this.log.debug(\"MCP request cancelled\", request.params);\n break;\n default:\n this.log.debug(`Unknown MCP notification: ${method}`);\n }\n }\n\n // -----------------------------------------------------------------------------------------------------------------\n // Protocol Handlers\n // -----------------------------------------------------------------------------------------------------------------\n\n protected handleInitialize(\n params: Record<string, unknown>,\n ): McpInitializeResult {\n const requested = params.protocolVersion;\n // Echo the client's version when supported, otherwise reply with our\n // preferred version (highest entry in SUPPORTED_PROTOCOL_VERSIONS).\n // The client can then decide to retry, downgrade, or disconnect.\n const negotiated = isSupportedProtocolVersion(requested)\n ? requested\n : SUPPORTED_PROTOCOL_VERSIONS[0];\n\n this.log.info(\"MCP client initializing\", {\n clientInfo: params.clientInfo,\n requestedProtocolVersion: requested,\n negotiatedProtocolVersion: negotiated,\n });\n\n this.initialized = true;\n this.negotiatedVersion = negotiated;\n\n return {\n protocolVersion: negotiated,\n capabilities: this.getCapabilities(),\n serverInfo: this.serverInfo,\n };\n }\n\n protected handlePing(): Record<string, never> {\n return {};\n }\n\n protected handleToolsList(): { tools: McpToolDescriptor[] } {\n return {\n tools: Array.from(this.tools.values()).map((t) => t.toDescriptor()),\n };\n }\n\n protected async handleToolsCall(\n params: Record<string, unknown>,\n context?: McpContext,\n ): Promise<McpToolCallResult> {\n const name = params.name as string;\n const args = (params.arguments ?? {}) as Record<string, unknown>;\n\n const tool = this.tools.get(name);\n if (!tool) {\n // McpToolNotFoundError is intentionally a JSON-RPC protocol error,\n // not a tool execution error — see SEP-1303 (only validation/runtime\n // failures of an existing tool are reported via isError: true).\n throw new McpToolNotFoundError(name);\n }\n\n try {\n const result = await tool.execute(args, context);\n\n // A tool WITHOUT an output schema may return raw MCP content blocks\n // (e.g. an `image` block) instead of JSON — used for binary payloads\n // like attachment previews. Recognized by the CallToolResult shape\n // (`{ content: McpContent[] }`); passed through verbatim. Tools that\n // declare an output schema always go through the structured path\n // below, so a JSON result that happens to carry a `content` array is\n // never mistaken for raw content.\n if (!tool.hasOutputSchema()) {\n const raw = this.asRawToolContent(result);\n if (raw) {\n return raw;\n }\n }\n\n const callResult: McpToolCallResult = {\n content: [\n {\n type: \"text\",\n text:\n typeof result === \"string\"\n ? result\n : JSON.stringify(result ?? null),\n },\n ],\n };\n\n // Spec 2025-06-18: when the tool declares an outputSchema, the server\n // MUST populate `structuredContent` with the validated result. The\n // text-stringified `content` block remains as a back-compat fallback.\n if (tool.hasOutputSchema() && result !== undefined) {\n callResult.structuredContent = result;\n }\n\n return callResult;\n } catch (error) {\n // Spec 2025-11-25 / SEP-1303: input-validation failures (and other\n // tool-runtime errors) are returned as Tool Execution Errors, not\n // JSON-RPC protocol errors, so the model can self-correct.\n // For TypeBox validation errors we surface the failing path so the\n // model knows which argument was malformed.\n if (error instanceof TypeBoxError) {\n const path = error.value?.path || \"/\";\n const message = error.value?.message || error.message;\n return {\n content: [\n {\n type: \"text\",\n text: `Validation error at ${path}: ${message}`,\n },\n ],\n structuredContent: {\n errors: [{ path, message }],\n },\n isError: true,\n };\n }\n\n return {\n content: [\n {\n type: \"text\",\n text: `Error: ${(error as Error).message}`,\n },\n ],\n isError: true,\n };\n }\n }\n\n /**\n * Recognize a tool handler's return value as a pre-built MCP tool result —\n * i.e. it already carries a `content` array of content blocks (text, image,\n * audio, resource, resource_link). Returns the normalized\n * {@link McpToolCallResult} when matched, or `undefined` to fall back to the\n * default JSON/text encoding. Only ever consulted for tools that did NOT\n * declare an output schema (see {@link handleToolCall}).\n */\n protected asRawToolContent(result: unknown): McpToolCallResult | undefined {\n if (!result || typeof result !== \"object\") {\n return undefined;\n }\n const candidate = result as {\n content?: unknown;\n isError?: unknown;\n _meta?: unknown;\n };\n if (!Array.isArray(candidate.content) || candidate.content.length === 0) {\n return undefined;\n }\n const allBlocks = candidate.content.every(\n (block): block is McpContent =>\n !!block &&\n typeof block === \"object\" &&\n typeof (block as { type?: unknown }).type === \"string\",\n );\n if (!allBlocks) {\n return undefined;\n }\n return {\n content: candidate.content as McpContent[],\n isError:\n typeof candidate.isError === \"boolean\" ? candidate.isError : undefined,\n _meta:\n candidate._meta && typeof candidate._meta === \"object\"\n ? (candidate._meta as Record<string, unknown>)\n : undefined,\n };\n }\n\n protected handleResourcesList(): { resources: McpResourceDescriptor[] } {\n return {\n resources: Array.from(this.resources.values()).map((r) =>\n r.toDescriptor(),\n ),\n };\n }\n\n protected async handleResourcesRead(\n params: Record<string, unknown>,\n context?: McpContext,\n ): Promise<McpResourceReadResult> {\n const uri = params.uri as string;\n\n const resource = this.resources.get(uri);\n if (!resource) {\n throw new McpResourceNotFoundError(uri);\n }\n\n const content = await resource.read(context);\n\n const resourceContent: McpResourceContent = {\n uri,\n mimeType: resource.mimeType,\n };\n\n if (content.text !== undefined) {\n resourceContent.text = content.text;\n }\n\n if (content.blob !== undefined) {\n // Convert binary to base64 for transport\n resourceContent.blob = Buffer.from(content.blob).toString(\"base64\");\n }\n\n return {\n contents: [resourceContent],\n };\n }\n\n protected handlePromptsList(): { prompts: McpPromptDescriptor[] } {\n return {\n prompts: Array.from(this.prompts.values()).map((p) => p.toDescriptor()),\n };\n }\n\n protected async handlePromptsGet(\n params: Record<string, unknown>,\n context?: McpContext,\n ): Promise<McpPromptGetResult> {\n const name = params.name as string;\n const args = (params.arguments ?? {}) as Record<string, string>;\n\n const prompt = this.prompts.get(name);\n if (!prompt) {\n throw new McpPromptNotFoundError(name);\n }\n\n const messages = await prompt.get(args, context);\n\n const mcpMessages: McpPromptMessage[] = messages.map((msg) => ({\n role: msg.role,\n content: {\n type: \"text\" as const,\n text: msg.content,\n },\n }));\n\n return {\n description: prompt.description,\n messages: mcpMessages,\n };\n }\n}\n","import {\n $inject,\n type Async,\n createPrimitive,\n KIND,\n Primitive,\n type Static,\n type TObject,\n t,\n} from \"alepha\";\nimport type {\n McpContext,\n McpIcon,\n McpPromptArgument,\n McpPromptDescriptor,\n PromptHandlerArgs,\n PromptMessage,\n} from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Creates an MCP prompt primitive for defining reusable prompt templates.\n *\n * Prompts allow you to define templated messages that can be filled in\n * with arguments at runtime. They're useful for creating consistent\n * interaction patterns.\n *\n * @example\n * ```ts\n * class Prompts {\n * greeting = $prompt({\n * description: \"Generate a personalized greeting\",\n * args: t.object({\n * name: t.text({ description: \"Name of the person to greet\" }),\n * style: t.optional(t.enum([\"formal\", \"casual\"])),\n * }),\n * handler: async ({ args }) => [\n * {\n * role: \"user\",\n * content: args.style === \"formal\"\n * ? `Please greet ${args.name} in a formal manner.`\n * : `Say hi to ${args.name}!`,\n * },\n * ],\n * });\n *\n * codeReview = $prompt({\n * description: \"Request a code review\",\n * args: t.object({\n * code: t.text({ description: \"The code to review\" }),\n * language: t.text({ description: \"Programming language\" }),\n * }),\n * handler: async ({ args }) => [\n * {\n * role: \"user\",\n * content: `Please review this ${args.language} code:\\n\\n${args.code}`,\n * },\n * ],\n * });\n * }\n * ```\n */\nexport const $prompt = <T extends TObject>(\n options: PromptPrimitiveOptions<T>,\n): PromptPrimitive<T> => {\n return createPrimitive(PromptPrimitive<T>, options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface PromptPrimitiveOptions<T extends TObject> {\n /**\n * The name of the prompt.\n *\n * If not provided, defaults to the property key where the prompt is declared.\n *\n * @example \"greeting\"\n * @example \"code-review\"\n */\n name?: string;\n\n /**\n * Human-friendly display title (spec 2025-11-25). Distinct from `name`,\n * which remains the programmatic identifier.\n */\n title?: string;\n\n /**\n * Description of what this prompt does.\n *\n * Helps users understand the purpose of the prompt.\n *\n * @example \"Generate a personalized greeting message\"\n */\n description?: string;\n\n /**\n * Optional icons surfaced in client UIs (spec 2025-11-25 / SEP-973).\n */\n icons?: McpIcon[];\n\n /**\n * TypeBox schema defining the prompt arguments.\n *\n * Each property in the schema becomes an argument that can be\n * filled in when the prompt is used.\n */\n args?: T;\n\n /**\n * Handler function that generates the prompt messages.\n *\n * Receives the validated arguments and returns an array of messages.\n *\n * @param args - Object containing validated arguments\n * @returns Array of prompt messages\n */\n handler: (args: PromptHandlerArgs<T>) => Async<PromptMessage[]>;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class PromptPrimitive<T extends TObject> extends Primitive<\n PromptPrimitiveOptions<T>\n> {\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * Returns the name of the prompt.\n */\n public get name(): string {\n return this.options.name ?? this.config.propertyKey;\n }\n\n /**\n * Returns the description of the prompt.\n */\n public get description(): string | undefined {\n return this.options.description;\n }\n\n protected onInit(): void {\n this.mcpServer.registerPrompt(this);\n }\n\n /**\n * Get the prompt messages with the given arguments.\n *\n * @param rawArgs - Raw arguments to validate and pass to the handler\n * @param context - Optional context from the transport layer\n * @returns Array of prompt messages\n */\n public async get(\n rawArgs: unknown,\n context?: McpContext,\n ): Promise<PromptMessage[]> {\n let args = (rawArgs ?? {}) as Static<T>;\n\n if (this.options.args) {\n args = this.alepha.codec.decode(this.options.args, rawArgs ?? {});\n }\n\n return this.options.handler({ args, context });\n }\n\n /**\n * Convert the prompt to an MCP prompt descriptor for protocol messages.\n */\n public toDescriptor(): McpPromptDescriptor {\n const descriptor: McpPromptDescriptor = {\n name: this.name,\n description: this.description,\n arguments: this.options.args\n ? this.schemaToArguments(this.options.args)\n : [],\n };\n if (this.options.title) descriptor.title = this.options.title;\n if (this.options.icons && this.options.icons.length > 0) {\n descriptor.icons = this.options.icons;\n }\n return descriptor;\n }\n\n /**\n * Convert a TypeBox schema to an array of prompt arguments.\n */\n protected schemaToArguments(schema: TObject): McpPromptArgument[] {\n const args: McpPromptArgument[] = [];\n\n for (const [name, propSchema] of Object.entries(schema.properties)) {\n const prop = propSchema as Record<string, unknown>;\n args.push({\n name,\n description: prop.description as string | undefined,\n required: !t.schema.isOptional(propSchema),\n });\n }\n\n return args;\n }\n}\n\n$prompt[KIND] = PromptPrimitive;\n","import { $inject, createPrimitive, KIND, Primitive } from \"alepha\";\nimport type {\n McpContext,\n McpIcon,\n McpResourceDescriptor,\n ResourceContent,\n ResourceHandler,\n} from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Creates an MCP resource primitive for exposing read-only data.\n *\n * Resources represent any kind of data that an LLM might want to read,\n * such as files, database records, API responses, or computed data.\n *\n * **Key Features**\n * - URI-based identification for resources\n * - Support for text and binary content\n * - MIME type specification\n * - Lazy loading via handler function\n *\n * @example\n * ```ts\n * class ProjectResources {\n * readme = $resource({\n * uri: \"file:///readme\",\n * description: \"Project README file\",\n * mimeType: \"text/markdown\",\n * handler: async () => ({\n * text: await fs.readFile(\"README.md\", \"utf-8\"),\n * }),\n * });\n *\n * config = $resource({\n * uri: \"config://app\",\n * name: \"Application Configuration\",\n * mimeType: \"application/json\",\n * handler: async () => ({\n * text: JSON.stringify(this.configService.getConfig()),\n * }),\n * });\n * }\n * ```\n */\nexport const $resource = (\n options: ResourcePrimitiveOptions,\n): ResourcePrimitive => {\n return createPrimitive(ResourcePrimitive, options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface ResourcePrimitiveOptions {\n /**\n * The URI that identifies this resource.\n *\n * URIs should follow a consistent scheme for your application.\n * Common patterns:\n * - `file:///path/to/file` - File system resources\n * - `db://table/id` - Database records\n * - `api://endpoint` - API responses\n * - `config://name` - Configuration values\n *\n * @example \"file:///readme.md\"\n * @example \"db://users/123\"\n */\n uri: string;\n\n /**\n * Human-readable name for the resource.\n *\n * If not provided, defaults to the property key where the resource is declared.\n *\n * @example \"Project README\"\n * @example \"User Profile\"\n */\n name?: string;\n\n /**\n * Human-friendly display title (spec 2025-11-25). Distinct from `name`,\n * which remains the programmatic identifier.\n */\n title?: string;\n\n /**\n * Optional icons surfaced in client UIs (spec 2025-11-25 / SEP-973).\n */\n icons?: McpIcon[];\n\n /**\n * Description of what this resource contains.\n *\n * Helps the LLM understand the purpose and content of the resource.\n *\n * @example \"The main README file for the project\"\n */\n description?: string;\n\n /**\n * MIME type of the resource content.\n *\n * Helps clients understand how to interpret the content.\n *\n * @default \"text/plain\"\n * @example \"text/markdown\"\n * @example \"application/json\"\n */\n mimeType?: string;\n\n /**\n * Handler function that returns the resource content.\n *\n * Called when the resource is read. Can return text or binary content.\n *\n * @returns Resource content with either `text` or `blob` property\n */\n handler: ResourceHandler;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class ResourcePrimitive extends Primitive<ResourcePrimitiveOptions> {\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * Returns the name of the resource.\n */\n public get name(): string {\n return this.options.name ?? this.config.propertyKey;\n }\n\n /**\n * Returns the URI of the resource.\n */\n public get uri(): string {\n return this.options.uri;\n }\n\n /**\n * Returns the description of the resource.\n */\n public get description(): string | undefined {\n return this.options.description;\n }\n\n /**\n * Returns the MIME type of the resource.\n */\n public get mimeType(): string {\n return this.options.mimeType ?? \"text/plain\";\n }\n\n protected onInit(): void {\n this.mcpServer.registerResource(this);\n }\n\n /**\n * Read the resource content.\n *\n * @param context - Optional context from the transport layer\n * @returns The resource content\n */\n public async read(context?: McpContext): Promise<ResourceContent> {\n return this.options.handler({ context });\n }\n\n /**\n * Convert the resource to an MCP resource descriptor for protocol messages.\n */\n public toDescriptor(): McpResourceDescriptor {\n const descriptor: McpResourceDescriptor = {\n uri: this.uri,\n name: this.name,\n description: this.description,\n mimeType: this.mimeType,\n };\n if (this.options.title) descriptor.title = this.options.title;\n if (this.options.icons && this.options.icons.length > 0) {\n descriptor.icons = this.options.icons;\n }\n return descriptor;\n }\n}\n\n$resource[KIND] = ResourcePrimitive;\n","import {\n $inject,\n type Async,\n createPrimitive,\n KIND,\n Primitive,\n type TObject,\n type TSchema,\n t,\n} from \"alepha\";\nimport type {\n McpContext,\n McpIcon,\n McpJsonSchema,\n McpToolAnnotations,\n McpToolDescriptor,\n ToolHandlerArgs,\n ToolHandlerResult,\n ToolPrimitiveSchema,\n} from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Creates an MCP tool primitive for defining callable functions.\n *\n * Tools are the primary way for LLMs to interact with external systems through MCP.\n * Each tool has a name, description, typed parameters, and a handler function.\n *\n * **Key Features**\n * - Full TypeScript inference for parameters and results\n * - Automatic schema validation using TypeBox\n * - JSON Schema generation for MCP protocol\n * - Integration with MCP server provider\n *\n * @example\n * ```ts\n * class CalculatorTools {\n * add = $tool({\n * description: \"Add two numbers together\",\n * schema: {\n * params: t.object({\n * a: t.number(),\n * b: t.number(),\n * }),\n * result: t.number(),\n * },\n * handler: async ({ params }) => {\n * return params.a + params.b;\n * },\n * });\n *\n * greet = $tool({\n * description: \"Generate a greeting message\",\n * schema: {\n * params: t.object({\n * name: t.text(),\n * }),\n * result: t.text(),\n * },\n * handler: async ({ params }) => {\n * return `Hello, ${params.name}!`;\n * },\n * });\n * }\n * ```\n */\nexport const $tool = <T extends ToolPrimitiveSchema>(\n options: ToolPrimitiveOptions<T>,\n): ToolPrimitive<T> => {\n return createPrimitive(ToolPrimitive<T>, options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface ToolPrimitiveOptions<T extends ToolPrimitiveSchema> {\n /**\n * The name of the tool.\n *\n * If not provided, defaults to the property key where the tool is declared.\n * Names should be descriptive and use kebab-case or snake_case.\n *\n * @example \"calculate-sum\"\n * @example \"get_weather\"\n */\n name?: string;\n\n /**\n * Human-friendly display title (spec 2025-11-25). Distinct from `name`,\n * which remains the programmatic identifier. Clients use `title` in\n * tool palettes / picker UIs.\n *\n * @example \"Search Lore\"\n */\n title?: string;\n\n /**\n * A human-readable description of what the tool does.\n *\n * This description is sent to the LLM to help it understand\n * when and how to use the tool. Be clear and specific.\n *\n * @example \"Calculate the sum of two numbers\"\n * @example \"Retrieve current weather data for a given location\"\n */\n description: string;\n\n /**\n * Behavior hints (spec 2025-03-26+). Clients use these to gate UI prompts\n * (e.g. require confirmation before a tool with `destructiveHint: true`).\n * None are guarantees — they are heuristics for the client, not the model.\n */\n annotations?: McpToolAnnotations;\n\n /**\n * Icons surfaced in client tool palettes / picker UIs (spec 2025-11-25).\n */\n icons?: McpIcon[];\n\n /**\n * TypeBox schema defining the tool's parameters and result type.\n *\n * - **params**: TObject schema for input parameters (optional)\n * - **result**: TSchema for the return value (optional)\n *\n * Schemas provide:\n * - Type inference for handler function\n * - Runtime validation of inputs\n * - JSON Schema generation for MCP protocol\n */\n schema?: T;\n\n /**\n * The handler function that executes when the tool is called.\n *\n * Receives validated parameters and returns the result.\n * Errors thrown here are caught and returned as MCP errors.\n *\n * @param args - Object containing validated params\n * @returns The tool result (can be async)\n */\n handler: (args: ToolHandlerArgs<T>) => Async<ToolHandlerResult<T>>;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class ToolPrimitive<T extends ToolPrimitiveSchema> extends Primitive<\n ToolPrimitiveOptions<T>\n> {\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * Returns the name of the tool.\n */\n public get name(): string {\n return this.options.name ?? this.config.propertyKey;\n }\n\n /**\n * Returns the description of the tool.\n */\n public get description(): string {\n return this.options.description;\n }\n\n /**\n * Whether the tool declared a result schema. When true, `tools/call`\n * responses include `structuredContent` populated with the validated\n * result (spec 2025-06-18).\n */\n public hasOutputSchema(): boolean {\n return !!this.options.schema?.result;\n }\n\n protected onInit(): void {\n this.mcpServer.registerTool(this);\n }\n\n /**\n * Execute the tool with the given parameters.\n *\n * @param params - Raw parameters to validate and pass to the handler\n * @param context - Optional context from the transport layer\n * @returns The tool result\n */\n public async execute(\n params: unknown,\n context?: McpContext,\n ): Promise<ToolHandlerResult<T>> {\n let validatedParams: any = params ?? {};\n\n // Validate params using alepha.codec if schema provided\n if (this.options.schema?.params) {\n validatedParams = this.alepha.codec.decode(\n this.options.schema.params,\n validatedParams,\n );\n }\n\n const result = await this.options.handler({\n params: validatedParams,\n context,\n });\n\n // Validate and encode result if schema provided\n if (this.options.schema?.result && result !== undefined) {\n return this.alepha.codec.encode(\n this.options.schema.result,\n result,\n ) as ToolHandlerResult<T>;\n }\n\n return result as ToolHandlerResult<T>;\n }\n\n /**\n * Convert the tool to an MCP tool descriptor for protocol messages.\n *\n * Emits the spec 2025-11-25 surface: `title`, `annotations`, `icons`,\n * and (when `schema.result` is defined) `outputSchema` so the server\n * can populate `structuredContent` on call results.\n */\n public toDescriptor(): McpToolDescriptor {\n const inputSchema: McpJsonSchema = this.options.schema?.params\n ? this.schemaToJsonSchema(this.options.schema.params)\n : { type: \"object\", properties: {}, required: [] };\n\n const descriptor: McpToolDescriptor = {\n name: this.name,\n description: this.description,\n inputSchema,\n };\n\n if (this.options.title) descriptor.title = this.options.title;\n if (this.options.annotations)\n descriptor.annotations = this.options.annotations;\n if (this.options.icons && this.options.icons.length > 0) {\n descriptor.icons = this.options.icons;\n }\n\n // Output schema is emitted when the tool declares `schema.result`,\n // unlocking structured content on tools/call responses.\n if (this.options.schema?.result) {\n const out = this.propertyToJsonSchema(this.options.schema.result);\n // The result schema may be a primitive — wrap so the descriptor\n // value is always a JSON Schema object with `type`.\n descriptor.outputSchema = (\n typeof out === \"object\" && out !== null && \"type\" in out\n ? out\n : { type: \"object\", properties: {}, required: [] }\n ) as McpJsonSchema;\n }\n\n return descriptor;\n }\n\n /**\n * Convert a TypeBox schema to JSON Schema format.\n *\n * Emits the 2020-12 dialect annotation at the root (spec 2025-11-25 /\n * SEP-1613 — JSON Schema 2020-12 is the default dialect for MCP).\n * The TypeBox shapes Alepha emits today are already 2020-12-compatible;\n * this is just the dialect declaration.\n */\n protected schemaToJsonSchema(\n schema: TObject,\n options?: { root?: boolean },\n ): McpJsonSchema {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n properties[key] = this.propertyToJsonSchema(propSchema as TSchema);\n\n // Check if property is required (not optional)\n if (!t.schema.isOptional(propSchema as TSchema)) {\n required.push(key);\n }\n }\n\n const result: McpJsonSchema = {\n type: \"object\",\n properties,\n required,\n };\n\n // Annotate the dialect on the root schema only (avoid noise on nested\n // sub-schemas where MCP doesn't expect $schema).\n if (options?.root !== false) {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n\n return result;\n }\n\n /**\n * Convert a single property schema to JSON Schema format.\n */\n protected propertyToJsonSchema(schema: TSchema): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n // Check for description on all types\n if (\"description\" in schema) {\n result.description = schema.description;\n }\n\n if (t.schema.isString(schema)) {\n result.type = \"string\";\n if (\"minLength\" in schema) result.minLength = schema.minLength;\n if (\"maxLength\" in schema) result.maxLength = schema.maxLength;\n if (\"pattern\" in schema) result.pattern = schema.pattern;\n if (\"enum\" in schema) result.enum = schema.enum;\n } else if (t.schema.isNumber(schema)) {\n result.type = \"number\";\n if (\"minimum\" in schema) result.minimum = schema.minimum;\n if (\"maximum\" in schema) result.maximum = schema.maximum;\n } else if (t.schema.isInteger(schema)) {\n result.type = \"integer\";\n if (\"minimum\" in schema) result.minimum = schema.minimum;\n if (\"maximum\" in schema) result.maximum = schema.maximum;\n } else if (t.schema.isBoolean(schema)) {\n result.type = \"boolean\";\n } else if (t.schema.isArray(schema)) {\n result.type = \"array\";\n if (\"items\" in schema) {\n result.items = this.propertyToJsonSchema(schema.items as TSchema);\n }\n } else if (t.schema.isObject(schema)) {\n Object.assign(result, this.schemaToJsonSchema(schema, { root: false }));\n } else if (t.schema.isUnsafe(schema) || t.schema.isOptional(schema)) {\n // Handle Unsafe types (like t.enum) and optional wrappers by checking the underlying type property\n const schemaAny = schema as { type?: string; enum?: unknown[] };\n if (schemaAny.type === \"string\") {\n result.type = \"string\";\n if (\"enum\" in schema) result.enum = schema.enum;\n if (\"pattern\" in schema) result.pattern = schema.pattern;\n } else if (schemaAny.type === \"number\") {\n result.type = \"number\";\n } else if (schemaAny.type === \"integer\") {\n result.type = \"integer\";\n } else if (schemaAny.type === \"boolean\") {\n result.type = \"boolean\";\n } else if (schemaAny.type === \"array\") {\n result.type = \"array\";\n } else if (schemaAny.type === \"object\") {\n result.type = \"object\";\n } else {\n // Fallback\n result.type = \"string\";\n }\n } else {\n // Fallback for other types\n result.type = \"string\";\n }\n\n return result;\n }\n}\n\n$tool[KIND] = ToolPrimitive;\n","import { $atom, $inject, $state, t } from \"alepha\";\nimport { $logger } from \"alepha/logger\";\nimport { $route } from \"alepha/server\";\nimport {\n createErrorResponse,\n createParseError,\n JsonRpcParseError,\n parseMessage,\n} from \"../helpers/jsonrpc.ts\";\nimport type { McpContext } from \"../interfaces/McpTypes.ts\";\nimport { McpServerProvider } from \"../providers/McpServerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport const mcpStreamableHttpOptions = $atom({\n name: \"alepha.mcp.streamableHttp.options\",\n description: \"Configuration options for the MCP Streamable HTTP transport.\",\n schema: t.object({\n /**\n * Path for the MCP endpoint. Single endpoint for both requests and\n * (optional) server-streamed responses, per spec 2025-03-26+.\n */\n path: t.text({ default: \"/mcp\" }),\n /**\n * Allow-list of `Origin` header values accepted on incoming requests.\n * Empty array (default) means \"allow any\". When set, browser-originated\n * requests with a non-matching `Origin` are rejected with 403 Forbidden,\n * blocking DNS-rebinding attacks against localhost MCP servers.\n *\n * Server-to-server callers (no `Origin` header) are always allowed.\n *\n * Spec 2025-11-25, PR #1439.\n */\n allowedOrigins: t.array(t.text(), { default: [] }),\n /**\n * When true, an unauthenticated POST to the MCP endpoint is rejected\n * with `401 Unauthorized` and an RFC 9728 `WWW-Authenticate` challenge\n * instead of being dispatched. MCP clients (Claude, etc.) rely on that\n * challenge to discover the OAuth authorization server.\n *\n * The transport stays OAuth-agnostic: it only knows \"auth is required\".\n * `$realm({ features: { oauth: true } })` flips this on automatically.\n *\n * @default false\n */\n requireAuth: t.boolean({ default: false }),\n /**\n * Path of the RFC 9728 protected-resource metadata document, advertised\n * (as an absolute URL, resolved against the request origin) in the\n * `WWW-Authenticate` challenge emitted when {@link requireAuth} rejects\n * a request.\n */\n resourceMetadataPath: t.text({\n default: \"/.well-known/oauth-protected-resource\",\n }),\n }),\n default: {\n path: \"/mcp\",\n allowedOrigins: [],\n requireAuth: false,\n resourceMetadataPath: \"/.well-known/oauth-protected-resource\",\n },\n});\n\n// Backward-compat alias for the legacy atom name. Prefer\n// `mcpStreamableHttpOptions` going forward; this re-export keeps existing\n// consumer imports compiling and will be removed once they migrate.\nexport const mcpSseOptions = mcpStreamableHttpOptions;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Streamable HTTP transport for MCP communication.\n *\n * Implements the 2025-03-26+ Streamable HTTP transport: a single `/mcp`\n * endpoint that accepts JSON-RPC over POST and returns either\n * `application/json` (single response, the default) or\n * `text/event-stream` (when the server wants to stream multiple messages).\n *\n * Designed for serverless deployment (Cloudflare Workers, etc.) — there is\n * no long-lived GET stream. GET on the endpoint returns 405 Method Not\n * Allowed; clients that want server-initiated push must rely on the POST\n * response stream when the server upgrades to SSE for that particular call.\n *\n * Spec compliance:\n * - 2025-06-18: validates `MCP-Protocol-Version` header on every request\n * after `initialize` against the version negotiated and stored on\n * `McpServerProvider`.\n * - 2025-11-25: rejects requests with a non-allow-listed `Origin` header\n * (PR #1439). See {@link mcpStreamableHttpOptions.allowedOrigins}.\n *\n * @example\n * ```ts\n * import { Alepha, run } from \"alepha\";\n * import { AlephaServer } from \"alepha/server\";\n * import { AlephaMcp, StreamableHttpMcpTransport } from \"alepha/mcp\";\n *\n * class MyTools {\n * // ... tool definitions\n * }\n *\n * run(\n * Alepha.create()\n * .with(AlephaServer)\n * .with(AlephaMcp)\n * .with(StreamableHttpMcpTransport)\n * .with(MyTools)\n * );\n * ```\n */\nexport class StreamableHttpMcpTransport {\n protected readonly log = $logger();\n protected readonly options = $state(mcpStreamableHttpOptions);\n protected readonly mcpServer = $inject(McpServerProvider);\n\n /**\n * GET on the MCP endpoint is not supported in this transport. Returning\n * 405 (rather than serving the legacy two-endpoint SSE pattern) is the\n * spec-allowed response for servers that don't offer server-initiated\n * push outside of an active POST.\n */\n notAllowed = $route({\n method: \"GET\",\n path: this.options.path,\n handler: (request) => {\n request.reply.status = 405;\n request.reply.headers.allow = \"POST\";\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify({\n error: \"Method Not Allowed. Use POST for MCP messages.\",\n });\n },\n });\n\n /**\n * POST endpoint for client-to-server JSON-RPC messages.\n * Returns `application/json` for single responses; tools that need to\n * stream progress would upgrade to `text/event-stream` (deferred until a\n * concrete need exists).\n */\n message = $route({\n method: \"POST\",\n path: this.options.path,\n schema: {\n body: t.json(),\n },\n handler: async (request) => {\n try {\n // Origin allow-list check (spec 2025-11-25 / PR #1439).\n const originRaw = request.headers.origin;\n const origin = Array.isArray(originRaw) ? originRaw[0] : originRaw;\n if (\n origin &&\n this.options.allowedOrigins.length > 0 &&\n !this.options.allowedOrigins.includes(origin)\n ) {\n this.log.warn(\"Rejected MCP request with non-allowed Origin\", {\n origin,\n allowed: this.options.allowedOrigins,\n });\n request.reply.status = 403;\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify({\n error: \"Forbidden: Origin not allowed\",\n });\n return;\n }\n\n // RFC 9728 / MCP auth (spec 2025-06-18+): when the endpoint is\n // OAuth-protected, an unauthenticated request is rejected with 401\n // and a `WWW-Authenticate` challenge pointing at the protected-\n // resource metadata. MCP clients (Claude, etc.) follow that\n // `resource_metadata` URL to discover the authorization server —\n // without it, discovery never starts. The URL MUST be absolute.\n if (this.options.requireAuth && !request.user) {\n const url =\n typeof request.url === \"string\"\n ? new URL(request.url)\n : request.url;\n const resourceMetadataUrl = `${url.protocol}//${url.host}${this.options.resourceMetadataPath}`;\n this.log.debug(\"Rejecting unauthenticated MCP request\", {\n resourceMetadataUrl,\n });\n request.reply.status = 401;\n request.reply.headers[\"www-authenticate\"] =\n `Bearer resource_metadata=\"${resourceMetadataUrl}\"`;\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify({\n error: \"Unauthorized\",\n });\n return;\n }\n\n const body =\n typeof request.body === \"string\"\n ? request.body\n : JSON.stringify(request.body);\n\n this.log.debug(\"MCP request body\", {\n body,\n bodyType: typeof request.body,\n });\n\n const rpcRequest = parseMessage(body);\n\n // Build context from request headers\n const headers = { ...request.headers } as Record<\n string,\n string | string[] | undefined\n >;\n\n // Spec 2025-06-18+: every HTTP request after `initialize` MUST carry\n // an `MCP-Protocol-Version` header matching the negotiated version.\n // Reject mismatches with 400 so the client doesn't silently drift.\n if (rpcRequest.method !== \"initialize\") {\n const headerRaw = headers[\"mcp-protocol-version\"];\n const headerVersion = Array.isArray(headerRaw)\n ? headerRaw[0]\n : headerRaw;\n if (\n headerVersion &&\n headerVersion !== this.mcpServer.negotiatedVersion\n ) {\n this.log.warn(\"MCP-Protocol-Version header mismatch\", {\n header: headerVersion,\n negotiated: this.mcpServer.negotiatedVersion,\n });\n request.reply.status = 400;\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify({\n error: `MCP-Protocol-Version mismatch: expected ${this.mcpServer.negotiatedVersion}, got ${headerVersion}`,\n });\n return;\n }\n }\n\n const context: McpContext = { headers };\n\n const response = await this.mcpServer.handleMessage(\n rpcRequest,\n context,\n );\n\n if (response) {\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify(response);\n } else {\n request.reply.status = 204;\n }\n } catch (error) {\n if (error instanceof JsonRpcParseError) {\n request.reply.status = 400;\n request.reply.headers[\"content-type\"] = \"application/json\";\n request.reply.body = JSON.stringify(\n createErrorResponse(0, createParseError(error.message)),\n );\n } else {\n this.log.error(\"Failed to process MCP message\", error);\n request.reply.status = 500;\n request.reply.body = JSON.stringify({\n error: (error as Error).message,\n });\n }\n }\n },\n });\n}\n\n/**\n * @deprecated Use {@link StreamableHttpMcpTransport}. The 2024-11-05\n * two-endpoint HTTP+SSE pattern was replaced by Streamable HTTP in spec\n * 2025-03-26. This alias is preserved for one release to ease migration.\n */\nexport const SseMcpTransport = StreamableHttpMcpTransport;\n","import { $module } from \"alepha\";\nimport { $prompt } from \"./primitives/$prompt.ts\";\nimport { $resource } from \"./primitives/$resource.ts\";\nimport { $tool } from \"./primitives/$tool.ts\";\nimport { McpServerProvider } from \"./providers/McpServerProvider.ts\";\nimport { StreamableHttpMcpTransport } from \"./transports/StreamableHttpMcpTransport.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport {\n McpError,\n McpErrorCodes,\n McpForbiddenError,\n McpInvalidParamsError,\n McpMethodNotFoundError,\n McpPromptNotFoundError,\n McpResourceNotFoundError,\n McpToolNotFoundError,\n McpUnauthorizedError,\n} from \"./errors/McpError.ts\";\nexport {\n createErrorResponse,\n createInternalError,\n createInvalidParamsError,\n createInvalidRequestError,\n createMethodNotFoundError,\n createNotification,\n createParseError,\n createResponse,\n isNotification,\n isSupportedProtocolVersion,\n isValidJsonRpcRequest,\n JSONRPC_VERSION,\n JsonRpcErrorCodes,\n JsonRpcParseError,\n MCP_PROTOCOL_VERSION,\n parseMessage,\n SUPPORTED_PROTOCOL_VERSIONS,\n type SupportedProtocolVersion,\n} from \"./helpers/jsonrpc.ts\";\nexport type {\n JsonRpcError,\n JsonRpcNotification,\n // JSON-RPC types\n JsonRpcRequest,\n JsonRpcResponse,\n // MCP protocol types\n McpCapabilities,\n McpClientInfo,\n McpContent,\n // Context type for auth/headers\n McpContext,\n McpInitializeParams,\n McpInitializeResult,\n McpJsonSchema,\n McpPromptArgument,\n McpPromptContent,\n // Prompt types\n McpPromptDescriptor,\n McpPromptGetParams,\n McpPromptGetResult,\n McpPromptMessage,\n McpResourceContent,\n // Resource types\n McpResourceDescriptor,\n McpResourceReadParams,\n McpResourceReadResult,\n McpServerInfo,\n McpToolCallParams,\n McpToolCallResult,\n // Tool types\n McpToolDescriptor,\n PromptHandler,\n PromptHandlerArgs,\n PromptMessage,\n ResourceContent,\n ResourceHandler,\n ResourceHandlerArgs,\n ToolHandler,\n ToolHandlerArgs,\n ToolHandlerResult,\n // Handler types\n ToolPrimitiveSchema,\n} from \"./interfaces/McpTypes.ts\";\nexport type { PromptPrimitiveOptions } from \"./primitives/$prompt.ts\";\nexport { $prompt, PromptPrimitive } from \"./primitives/$prompt.ts\";\nexport type { ResourcePrimitiveOptions } from \"./primitives/$resource.ts\";\nexport { $resource, ResourcePrimitive } from \"./primitives/$resource.ts\";\nexport type { ToolPrimitiveOptions } from \"./primitives/$tool.ts\";\nexport { $tool, ToolPrimitive } from \"./primitives/$tool.ts\";\nexport { McpServerProvider } from \"./providers/McpServerProvider.ts\";\nexport {\n mcpSseOptions,\n mcpStreamableHttpOptions,\n SseMcpTransport,\n StreamableHttpMcpTransport,\n} from \"./transports/StreamableHttpMcpTransport.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Model Context Protocol for AI tool integration.\n *\n * **Features:**\n * - MCP resource definitions\n * - MCP tool definitions\n * - MCP prompt definitions\n * - JSON-RPC protocol\n * - Streamable HTTP transport (spec 2025-03-26+)\n *\n * @module alepha.mcp\n */\nexport const AlephaMcp = $module({\n name: \"alepha.mcp\",\n primitives: [$tool, $resource, $prompt],\n services: [McpServerProvider],\n // Transports are opt-in — user wires the one(s) they need via alepha.with(StreamableHttpMcpTransport).\n variants: [StreamableHttpMcpTransport],\n});\n"],"mappings":";;;;AAYA,MAAa,kBAAkB;;;;;AAM/B,MAAa,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MAAM,SAAS;KACvB,QAAQ,MAAM,QAAQ,kBAAkB;KACxC,QAAQ,MAAM,OAAO,KAAK,UACxB,oBAAoB,GAAG,iBAAiB,MAAM,OAAO,CAAC,CACxD;IACF,OAAO;KACL,KAAK,IAAI,MAAM,iCAAiC,KAAK;KACrD,QAAQ,MAAM,SAAS;KACvB,QAAQ,MAAM,OAAO,KAAK,UAAU,EAClC,OAAQ,MAAgB,QAC1B,CAAC;IACH;GACF;EACF;CACF,CAAC;AACH;;;;;;AAOA,MAAa,kBAAkB;;;;;;;;;;;;;;;ACjK/B,MAAa,YAAY,QAAQ;CAC/B,MAAM;CACN,YAAY;EAAC;EAAO;EAAW;CAAO;CACtC,UAAU,CAAC,iBAAiB;CAE5B,UAAU,CAAC,0BAA0B;AACvC,CAAC"}
|
|
@@ -19,7 +19,6 @@ declare class FormModel<T extends TObject> {
|
|
|
19
19
|
protected readonly initialValues: Record<string, any>;
|
|
20
20
|
protected submitInProgress: boolean;
|
|
21
21
|
input: SchemaToInput<T>;
|
|
22
|
-
get submitting(): boolean;
|
|
23
22
|
constructor(id: string, options: FormCtrlOptions<T>);
|
|
24
23
|
/**
|
|
25
24
|
* Extract default values from a TypeBox schema.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/react/form/services/FormModel.ts","../../../src/react/form/components/FormState.tsx","../../../src/react/form/errors/FormValidationError.ts","../../../src/react/form/hooks/useFieldValue.ts","../../../src/react/form/hooks/useForm.ts","../../../src/react/form/hooks/useFormQuerySync.ts","../../../src/react/form/hooks/useFormState.ts","../../../src/react/form/hooks/useFormValues.ts","../../../src/react/form/services/parseField.ts","../../../src/react/form/services/prettyName.ts","../../../src/react/form/index.ts"],"mappings":";;;;;AAoBA;;;;;;;cAAa,SAAA,WAAoB,OAAA;EAAA,
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/react/form/services/FormModel.ts","../../../src/react/form/components/FormState.tsx","../../../src/react/form/errors/FormValidationError.ts","../../../src/react/form/hooks/useFieldValue.ts","../../../src/react/form/hooks/useForm.ts","../../../src/react/form/hooks/useFormQuerySync.ts","../../../src/react/form/hooks/useFormState.ts","../../../src/react/form/hooks/useFormValues.ts","../../../src/react/form/services/parseField.ts","../../../src/react/form/services/prettyName.ts","../../../src/react/form/index.ts"],"mappings":";;;;;AAoBA;;;;;;;cAAa,SAAA,WAAoB,OAAA;EAAA,SAUb,EAAA;EAAA,SACA,OAAA,EAAS,eAAA,CAAgB,CAAA;EAAA,mBAVxB,GAAA,0BAAG,MAAA;EAAA,mBACH,MAAA,EAAM,MAAA;EAAA,mBACN,MAAA,EAAQ,MAAA;EAAA,mBACR,aAAA,EAAe,MAAA;EAAA,UACxB,gBAAA;EAEH,KAAA,EAAO,aAAA,CAAc,CAAA;cAGV,EAAA,UACA,OAAA,EAAS,eAAA,CAAgB,CAAA;EA+EtB;;;;EAAA,UA7CX,qBAAA,CACR,MAAA,EAAQ,OAAA,EACR,MAAA,YACC,MAAA;EAAA,IA8BQ,aAAA,IAAiB,MAAA;EAAA,IAIjB,KAAA;;;oBAIS,aAAA;qBAIC,aAAA;EAAA;EAAA,SAIL,gBAAA,GAAoB,MAAA,EAAQ,MAAA;EAAA,SAmC5B,KAAA,GAAS,KAAA,GAAQ,aAAA;EAAA,SA0BjB,MAAA,QAAM,OAAA;EAkLD;;;;EAAA,UApFX,iBAAA,CAAkB,KAAA,EAAO,MAAA,gBAAsB,MAAA;EA0F9C;;;;EAAA,UAtED,sBAAA,CACR,MAAA,EAAQ,MAAA,eACR,GAAA,UACA,KAAA;EAAA,UAoBQ,qBAAA,WAAgC,OAAA,EACxC,OAAA,EAAS,eAAA,CAAgB,CAAA,GACzB,MAAA,EAAQ,OAAA,EACR,OAAA;IACE,MAAA;IACA,KAAA,EAAO,MAAA;EAAA,IAER,aAAA,CAAc,CAAA;EAAA,UAiCP,qBAAA,WAAgC,OAAA,EACxC,IAAA,QAAY,MAAA,CAAO,C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KAAA;EACA,WAAA;EACA,KAAA;EACA,QAAA;EACA,IAAA;EACA,MAAA;EACA,MAAA;EACA,OAAA;EACA,QAAA;EACA,gBAAA;EACA,IAAA;EACA,QAAA,GAAW,QAAA;EACX,WAAA,EAAa,gBAAA;EACb,MAAA;EACA,MAAA,EAAQ,OAAA;ER4QE;;;;;EQtQV,OAAA;AAAA;AAAA,UAGe,iBAAA;EACf,KAAA;EACA,WAAA;EACA,KAAA,GAAQ,KAAK;AAAA;;;;;;;;cAUF,UAAA,GACX,KAAA,EAAO,cAAA,EACP,OAAA,GAAS,iBAAA,KACR,SAAA;;;;;;;ARnDH;;;;;;;cSTa,UAAA,GAAc,IAAY;;;;YCO3B,KAAA;IACR,aAAA;MACE,EAAA;MACA,IAAA;MACA,KAAA;MVSuB;;;;MUJvB,OAAA;IAAA;IAEF,mBAAA;MAAuB,EAAA;IAAA;IACvB,qBAAA;MAAyB,EAAA;MAAY,MAAA,EAAQ,MAAA;IAAA;IAC7C,mBAAA;MAAuB,EAAA;MAAY,KAAA,EAAO,KAAK;IAAA;IAC/C,iBAAA;MAAqB,EAAA;IAAA;IACrB,YAAA;MAAgB,EAAA;IAAA;EAAA;AAAA;;;;;;;;;;;;;cAkBP,eAAA,mBAAe,OAAA,kBAAA,MAAA"}
|
package/dist/react/form/index.js
CHANGED
|
@@ -127,9 +127,6 @@ var FormModel = class {
|
|
|
127
127
|
initialValues = {};
|
|
128
128
|
submitInProgress = false;
|
|
129
129
|
input;
|
|
130
|
-
get submitting() {
|
|
131
|
-
return this.submitInProgress;
|
|
132
|
-
}
|
|
133
130
|
constructor(id, options) {
|
|
134
131
|
this.id = id;
|
|
135
132
|
this.options = options;
|
|
@@ -219,8 +216,8 @@ var FormModel = class {
|
|
|
219
216
|
await this.alepha.events.emit("react:action:begin", {
|
|
220
217
|
type: "form",
|
|
221
218
|
id: this.id
|
|
222
|
-
});
|
|
223
|
-
await this.alepha.events.emit("form:submit:begin", { id: this.id });
|
|
219
|
+
}, { catch: true });
|
|
220
|
+
await this.alepha.events.emit("form:submit:begin", { id: this.id }, { catch: true });
|
|
224
221
|
this.submitInProgress = true;
|
|
225
222
|
const options = this.options;
|
|
226
223
|
try {
|
|
@@ -230,31 +227,35 @@ var FormModel = class {
|
|
|
230
227
|
await this.alepha.events.emit("react:action:success", {
|
|
231
228
|
type: "form",
|
|
232
229
|
id: this.id
|
|
233
|
-
});
|
|
230
|
+
}, { catch: true });
|
|
234
231
|
await this.alepha.events.emit("form:submit:success", {
|
|
235
232
|
id: this.id,
|
|
236
233
|
values
|
|
237
|
-
});
|
|
234
|
+
}, { catch: true });
|
|
238
235
|
} catch (error) {
|
|
239
236
|
this.log.error("Form submission error:", error);
|
|
240
|
-
|
|
237
|
+
try {
|
|
238
|
+
options.onError?.(error);
|
|
239
|
+
} catch (handlerError) {
|
|
240
|
+
this.log.error("Form onError handler threw:", handlerError);
|
|
241
|
+
}
|
|
241
242
|
await this.alepha.events.emit("react:action:error", {
|
|
242
243
|
type: "form",
|
|
243
244
|
id: this.id,
|
|
244
245
|
error
|
|
245
|
-
});
|
|
246
|
+
}, { catch: true });
|
|
246
247
|
await this.alepha.events.emit("form:submit:error", {
|
|
247
248
|
error,
|
|
248
249
|
id: this.id
|
|
249
|
-
});
|
|
250
|
+
}, { catch: true });
|
|
250
251
|
} finally {
|
|
251
252
|
this.submitInProgress = false;
|
|
253
|
+
await this.alepha.events.emit("react:action:end", {
|
|
254
|
+
type: "form",
|
|
255
|
+
id: this.id
|
|
256
|
+
}, { catch: true });
|
|
257
|
+
await this.alepha.events.emit("form:submit:end", { id: this.id }, { catch: true });
|
|
252
258
|
}
|
|
253
|
-
await this.alepha.events.emit("react:action:end", {
|
|
254
|
-
type: "form",
|
|
255
|
-
id: this.id
|
|
256
|
-
});
|
|
257
|
-
await this.alepha.events.emit("form:submit:end", { id: this.id });
|
|
258
259
|
};
|
|
259
260
|
/**
|
|
260
261
|
* Restructures flat keys like "address.city" into nested objects like { address: { city: ... } }
|