alepha 0.13.8 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/dist/api/audits/index.d.ts +418 -338
  2. package/dist/api/audits/index.d.ts.map +1 -0
  3. package/dist/api/files/index.d.ts +81 -1
  4. package/dist/api/files/index.d.ts.map +1 -0
  5. package/dist/api/jobs/index.d.ts +107 -27
  6. package/dist/api/jobs/index.d.ts.map +1 -0
  7. package/dist/api/notifications/index.d.ts +21 -1
  8. package/dist/api/notifications/index.d.ts.map +1 -0
  9. package/dist/api/parameters/index.d.ts +455 -8
  10. package/dist/api/parameters/index.d.ts.map +1 -0
  11. package/dist/api/users/index.d.ts +844 -840
  12. package/dist/api/users/index.d.ts.map +1 -0
  13. package/dist/api/verifications/index.d.ts.map +1 -0
  14. package/dist/batch/index.d.ts.map +1 -0
  15. package/dist/bucket/index.d.ts.map +1 -0
  16. package/dist/cache/core/index.d.ts.map +1 -0
  17. package/dist/cache/redis/index.d.ts.map +1 -0
  18. package/dist/cli/index.d.ts +254 -59
  19. package/dist/cli/index.d.ts.map +1 -0
  20. package/dist/cli/index.js +499 -127
  21. package/dist/cli/index.js.map +1 -1
  22. package/dist/command/index.d.ts +217 -10
  23. package/dist/command/index.d.ts.map +1 -0
  24. package/dist/command/index.js +350 -74
  25. package/dist/command/index.js.map +1 -1
  26. package/dist/core/index.browser.js +1334 -1318
  27. package/dist/core/index.browser.js.map +1 -1
  28. package/dist/core/index.d.ts +76 -72
  29. package/dist/core/index.d.ts.map +1 -0
  30. package/dist/core/index.js +1337 -1321
  31. package/dist/core/index.js.map +1 -1
  32. package/dist/core/index.native.js +1337 -1321
  33. package/dist/core/index.native.js.map +1 -1
  34. package/dist/datetime/index.d.ts.map +1 -0
  35. package/dist/email/index.d.ts.map +1 -0
  36. package/dist/fake/index.d.ts.map +1 -0
  37. package/dist/file/index.d.ts.map +1 -0
  38. package/dist/file/index.js.map +1 -1
  39. package/dist/lock/core/index.d.ts.map +1 -0
  40. package/dist/lock/redis/index.d.ts.map +1 -0
  41. package/dist/logger/index.d.ts +1 -0
  42. package/dist/logger/index.d.ts.map +1 -0
  43. package/dist/mcp/index.d.ts +820 -0
  44. package/dist/mcp/index.d.ts.map +1 -0
  45. package/dist/mcp/index.js +978 -0
  46. package/dist/mcp/index.js.map +1 -0
  47. package/dist/orm/index.d.ts +234 -107
  48. package/dist/orm/index.d.ts.map +1 -0
  49. package/dist/orm/index.js +376 -316
  50. package/dist/orm/index.js.map +1 -1
  51. package/dist/queue/core/index.d.ts +4 -4
  52. package/dist/queue/core/index.d.ts.map +1 -0
  53. package/dist/queue/redis/index.d.ts.map +1 -0
  54. package/dist/queue/redis/index.js +2 -4
  55. package/dist/queue/redis/index.js.map +1 -1
  56. package/dist/redis/index.d.ts +400 -29
  57. package/dist/redis/index.d.ts.map +1 -0
  58. package/dist/redis/index.js +412 -21
  59. package/dist/redis/index.js.map +1 -1
  60. package/dist/retry/index.d.ts.map +1 -0
  61. package/dist/router/index.d.ts.map +1 -0
  62. package/dist/scheduler/index.d.ts +6 -6
  63. package/dist/scheduler/index.d.ts.map +1 -0
  64. package/dist/security/index.d.ts +28 -28
  65. package/dist/security/index.d.ts.map +1 -0
  66. package/dist/server/auth/index.d.ts +155 -155
  67. package/dist/server/auth/index.d.ts.map +1 -0
  68. package/dist/server/cache/index.d.ts.map +1 -0
  69. package/dist/server/compress/index.d.ts.map +1 -0
  70. package/dist/server/cookies/index.d.ts.map +1 -0
  71. package/dist/server/core/index.d.ts +0 -1
  72. package/dist/server/core/index.d.ts.map +1 -0
  73. package/dist/server/core/index.js.map +1 -1
  74. package/dist/server/cors/index.d.ts.map +1 -0
  75. package/dist/server/health/index.d.ts +17 -17
  76. package/dist/server/health/index.d.ts.map +1 -0
  77. package/dist/server/helmet/index.d.ts +4 -1
  78. package/dist/server/helmet/index.d.ts.map +1 -0
  79. package/dist/server/links/index.d.ts +33 -33
  80. package/dist/server/links/index.d.ts.map +1 -0
  81. package/dist/server/metrics/index.d.ts.map +1 -0
  82. package/dist/server/multipart/index.d.ts.map +1 -0
  83. package/dist/server/multipart/index.js.map +1 -1
  84. package/dist/server/proxy/index.d.ts.map +1 -0
  85. package/dist/server/proxy/index.js.map +1 -1
  86. package/dist/server/rate-limit/index.d.ts.map +1 -0
  87. package/dist/server/security/index.d.ts +9 -9
  88. package/dist/server/security/index.d.ts.map +1 -0
  89. package/dist/server/static/index.d.ts.map +1 -0
  90. package/dist/server/swagger/index.d.ts.map +1 -0
  91. package/dist/sms/index.d.ts.map +1 -0
  92. package/dist/thread/index.d.ts.map +1 -0
  93. package/dist/topic/core/index.d.ts.map +1 -0
  94. package/dist/topic/redis/index.d.ts.map +1 -0
  95. package/dist/topic/redis/index.js +3 -3
  96. package/dist/topic/redis/index.js.map +1 -1
  97. package/dist/vite/index.d.ts +10 -2
  98. package/dist/vite/index.d.ts.map +1 -0
  99. package/dist/vite/index.js +45 -20
  100. package/dist/vite/index.js.map +1 -1
  101. package/dist/websocket/index.d.ts.map +1 -0
  102. package/package.json +9 -4
  103. package/src/cli/apps/AlephaCli.ts +10 -3
  104. package/src/cli/apps/AlephaPackageBuilderCli.ts +15 -8
  105. package/src/cli/assets/mainTs.ts +9 -10
  106. package/src/cli/atoms/changelogOptions.ts +45 -0
  107. package/src/cli/commands/ChangelogCommands.ts +259 -0
  108. package/src/cli/commands/DeployCommands.ts +118 -0
  109. package/src/cli/commands/DrizzleCommands.ts +230 -10
  110. package/src/cli/commands/ViteCommands.ts +47 -23
  111. package/src/cli/defineConfig.ts +15 -0
  112. package/src/cli/index.ts +3 -0
  113. package/src/cli/services/AlephaCliUtils.ts +10 -154
  114. package/src/cli/services/GitMessageParser.ts +77 -0
  115. package/src/command/helpers/EnvUtils.ts +37 -0
  116. package/src/command/index.ts +3 -1
  117. package/src/command/primitives/$command.ts +172 -6
  118. package/src/command/providers/CliProvider.ts +499 -95
  119. package/src/core/Alepha.ts +1 -1
  120. package/src/core/providers/SchemaValidator.ts +23 -1
  121. package/src/file/providers/NodeFileSystemProvider.ts +3 -1
  122. package/src/mcp/errors/McpError.ts +72 -0
  123. package/src/mcp/helpers/jsonrpc.ts +163 -0
  124. package/src/mcp/index.ts +132 -0
  125. package/src/mcp/interfaces/McpTypes.ts +248 -0
  126. package/src/mcp/primitives/$prompt.ts +188 -0
  127. package/src/mcp/primitives/$resource.ts +171 -0
  128. package/src/mcp/primitives/$tool.ts +285 -0
  129. package/src/mcp/providers/McpServerProvider.ts +382 -0
  130. package/src/mcp/transports/SseMcpTransport.ts +172 -0
  131. package/src/mcp/transports/StdioMcpTransport.ts +126 -0
  132. package/src/orm/index.ts +20 -4
  133. package/src/orm/interfaces/PgQueryWhere.ts +1 -26
  134. package/src/orm/providers/drivers/BunPostgresProvider.ts +225 -0
  135. package/src/orm/providers/drivers/BunSqliteProvider.ts +180 -0
  136. package/src/orm/providers/drivers/CloudflareD1Provider.ts +164 -0
  137. package/src/orm/providers/drivers/DatabaseProvider.ts +25 -0
  138. package/src/orm/providers/drivers/NodePostgresProvider.ts +0 -25
  139. package/src/orm/providers/drivers/NodeSqliteProvider.ts +3 -1
  140. package/src/orm/services/QueryManager.ts +10 -125
  141. package/src/queue/redis/providers/RedisQueueProvider.ts +2 -7
  142. package/src/redis/index.ts +65 -3
  143. package/src/redis/providers/BunRedisProvider.ts +304 -0
  144. package/src/redis/providers/BunRedisSubscriberProvider.ts +94 -0
  145. package/src/redis/providers/NodeRedisProvider.ts +280 -0
  146. package/src/redis/providers/NodeRedisSubscriberProvider.ts +94 -0
  147. package/src/redis/providers/RedisProvider.ts +134 -140
  148. package/src/redis/providers/RedisSubscriberProvider.ts +58 -49
  149. package/src/server/core/providers/BunHttpServerProvider.ts +0 -3
  150. package/src/server/core/providers/ServerBodyParserProvider.ts +3 -1
  151. package/src/server/core/providers/ServerProvider.ts +7 -4
  152. package/src/server/multipart/providers/ServerMultipartProvider.ts +3 -1
  153. package/src/server/proxy/providers/ServerProxyProvider.ts +1 -1
  154. package/src/topic/redis/providers/RedisTopicProvider.ts +3 -3
  155. package/src/vite/plugins/viteAlephaBuild.ts +8 -2
  156. package/src/vite/plugins/viteAlephaDev.ts +6 -2
  157. package/src/vite/tasks/buildServer.ts +2 -1
  158. package/src/vite/tasks/generateCloudflare.ts +43 -15
  159. package/src/vite/tasks/runAlepha.ts +1 -0
  160. package/src/orm/services/PgJsonQueryManager.ts +0 -511
@@ -0,0 +1,188 @@
1
+ import {
2
+ $inject,
3
+ type Async,
4
+ createPrimitive,
5
+ KIND,
6
+ Primitive,
7
+ type Static,
8
+ type TObject,
9
+ t,
10
+ } from "alepha";
11
+ import type {
12
+ McpContext,
13
+ McpPromptArgument,
14
+ McpPromptDescriptor,
15
+ PromptHandlerArgs,
16
+ PromptMessage,
17
+ } from "../interfaces/McpTypes.ts";
18
+ import { McpServerProvider } from "../providers/McpServerProvider.ts";
19
+
20
+ // ---------------------------------------------------------------------------------------------------------------------
21
+
22
+ /**
23
+ * Creates an MCP prompt primitive for defining reusable prompt templates.
24
+ *
25
+ * Prompts allow you to define templated messages that can be filled in
26
+ * with arguments at runtime. They're useful for creating consistent
27
+ * interaction patterns.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * class Prompts {
32
+ * greeting = $prompt({
33
+ * description: "Generate a personalized greeting",
34
+ * args: t.object({
35
+ * name: t.text({ description: "Name of the person to greet" }),
36
+ * style: t.optional(t.enum(["formal", "casual"])),
37
+ * }),
38
+ * handler: async ({ args }) => [
39
+ * {
40
+ * role: "user",
41
+ * content: args.style === "formal"
42
+ * ? `Please greet ${args.name} in a formal manner.`
43
+ * : `Say hi to ${args.name}!`,
44
+ * },
45
+ * ],
46
+ * });
47
+ *
48
+ * codeReview = $prompt({
49
+ * description: "Request a code review",
50
+ * args: t.object({
51
+ * code: t.text({ description: "The code to review" }),
52
+ * language: t.text({ description: "Programming language" }),
53
+ * }),
54
+ * handler: async ({ args }) => [
55
+ * {
56
+ * role: "user",
57
+ * content: `Please review this ${args.language} code:\n\n${args.code}`,
58
+ * },
59
+ * ],
60
+ * });
61
+ * }
62
+ * ```
63
+ */
64
+ export const $prompt = <T extends TObject>(
65
+ options: PromptPrimitiveOptions<T>,
66
+ ): PromptPrimitive<T> => {
67
+ return createPrimitive(PromptPrimitive<T>, options);
68
+ };
69
+
70
+ // ---------------------------------------------------------------------------------------------------------------------
71
+
72
+ export interface PromptPrimitiveOptions<T extends TObject> {
73
+ /**
74
+ * The name of the prompt.
75
+ *
76
+ * If not provided, defaults to the property key where the prompt is declared.
77
+ *
78
+ * @example "greeting"
79
+ * @example "code-review"
80
+ */
81
+ name?: string;
82
+
83
+ /**
84
+ * Description of what this prompt does.
85
+ *
86
+ * Helps users understand the purpose of the prompt.
87
+ *
88
+ * @example "Generate a personalized greeting message"
89
+ */
90
+ description?: string;
91
+
92
+ /**
93
+ * TypeBox schema defining the prompt arguments.
94
+ *
95
+ * Each property in the schema becomes an argument that can be
96
+ * filled in when the prompt is used.
97
+ */
98
+ args?: T;
99
+
100
+ /**
101
+ * Handler function that generates the prompt messages.
102
+ *
103
+ * Receives the validated arguments and returns an array of messages.
104
+ *
105
+ * @param args - Object containing validated arguments
106
+ * @returns Array of prompt messages
107
+ */
108
+ handler: (args: PromptHandlerArgs<T>) => Async<PromptMessage[]>;
109
+ }
110
+
111
+ // ---------------------------------------------------------------------------------------------------------------------
112
+
113
+ export class PromptPrimitive<T extends TObject> extends Primitive<
114
+ PromptPrimitiveOptions<T>
115
+ > {
116
+ protected readonly mcpServer = $inject(McpServerProvider);
117
+
118
+ /**
119
+ * Returns the name of the prompt.
120
+ */
121
+ public get name(): string {
122
+ return this.options.name ?? this.config.propertyKey;
123
+ }
124
+
125
+ /**
126
+ * Returns the description of the prompt.
127
+ */
128
+ public get description(): string | undefined {
129
+ return this.options.description;
130
+ }
131
+
132
+ protected onInit(): void {
133
+ this.mcpServer.registerPrompt(this);
134
+ }
135
+
136
+ /**
137
+ * Get the prompt messages with the given arguments.
138
+ *
139
+ * @param rawArgs - Raw arguments to validate and pass to the handler
140
+ * @param context - Optional context from the transport layer
141
+ * @returns Array of prompt messages
142
+ */
143
+ public async get(
144
+ rawArgs: unknown,
145
+ context?: McpContext,
146
+ ): Promise<PromptMessage[]> {
147
+ let args = (rawArgs ?? {}) as Static<T>;
148
+
149
+ if (this.options.args) {
150
+ args = this.alepha.codec.decode(this.options.args, rawArgs ?? {});
151
+ }
152
+
153
+ return this.options.handler({ args, context });
154
+ }
155
+
156
+ /**
157
+ * Convert the prompt to an MCP prompt descriptor for protocol messages.
158
+ */
159
+ public toDescriptor(): McpPromptDescriptor {
160
+ return {
161
+ name: this.name,
162
+ description: this.description,
163
+ arguments: this.options.args
164
+ ? this.schemaToArguments(this.options.args)
165
+ : [],
166
+ };
167
+ }
168
+
169
+ /**
170
+ * Convert a TypeBox schema to an array of prompt arguments.
171
+ */
172
+ protected schemaToArguments(schema: TObject): McpPromptArgument[] {
173
+ const args: McpPromptArgument[] = [];
174
+
175
+ for (const [name, propSchema] of Object.entries(schema.properties)) {
176
+ const prop = propSchema as Record<string, unknown>;
177
+ args.push({
178
+ name,
179
+ description: prop.description as string | undefined,
180
+ required: !t.schema.isOptional(propSchema),
181
+ });
182
+ }
183
+
184
+ return args;
185
+ }
186
+ }
187
+
188
+ $prompt[KIND] = PromptPrimitive;
@@ -0,0 +1,171 @@
1
+ import { $inject, createPrimitive, KIND, Primitive } from "alepha";
2
+ import type {
3
+ McpContext,
4
+ McpResourceDescriptor,
5
+ ResourceContent,
6
+ ResourceHandler,
7
+ } from "../interfaces/McpTypes.ts";
8
+ import { McpServerProvider } from "../providers/McpServerProvider.ts";
9
+
10
+ // ---------------------------------------------------------------------------------------------------------------------
11
+
12
+ /**
13
+ * Creates an MCP resource primitive for exposing read-only data.
14
+ *
15
+ * Resources represent any kind of data that an LLM might want to read,
16
+ * such as files, database records, API responses, or computed data.
17
+ *
18
+ * **Key Features**
19
+ * - URI-based identification for resources
20
+ * - Support for text and binary content
21
+ * - MIME type specification
22
+ * - Lazy loading via handler function
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * class ProjectResources {
27
+ * readme = $resource({
28
+ * uri: "file:///readme",
29
+ * description: "Project README file",
30
+ * mimeType: "text/markdown",
31
+ * handler: async () => ({
32
+ * text: await fs.readFile("README.md", "utf-8"),
33
+ * }),
34
+ * });
35
+ *
36
+ * config = $resource({
37
+ * uri: "config://app",
38
+ * name: "Application Configuration",
39
+ * mimeType: "application/json",
40
+ * handler: async () => ({
41
+ * text: JSON.stringify(this.configService.getConfig()),
42
+ * }),
43
+ * });
44
+ * }
45
+ * ```
46
+ */
47
+ export const $resource = (
48
+ options: ResourcePrimitiveOptions,
49
+ ): ResourcePrimitive => {
50
+ return createPrimitive(ResourcePrimitive, options);
51
+ };
52
+
53
+ // ---------------------------------------------------------------------------------------------------------------------
54
+
55
+ export interface ResourcePrimitiveOptions {
56
+ /**
57
+ * The URI that identifies this resource.
58
+ *
59
+ * URIs should follow a consistent scheme for your application.
60
+ * Common patterns:
61
+ * - `file:///path/to/file` - File system resources
62
+ * - `db://table/id` - Database records
63
+ * - `api://endpoint` - API responses
64
+ * - `config://name` - Configuration values
65
+ *
66
+ * @example "file:///readme.md"
67
+ * @example "db://users/123"
68
+ */
69
+ uri: string;
70
+
71
+ /**
72
+ * Human-readable name for the resource.
73
+ *
74
+ * If not provided, defaults to the property key where the resource is declared.
75
+ *
76
+ * @example "Project README"
77
+ * @example "User Profile"
78
+ */
79
+ name?: string;
80
+
81
+ /**
82
+ * Description of what this resource contains.
83
+ *
84
+ * Helps the LLM understand the purpose and content of the resource.
85
+ *
86
+ * @example "The main README file for the project"
87
+ */
88
+ description?: string;
89
+
90
+ /**
91
+ * MIME type of the resource content.
92
+ *
93
+ * Helps clients understand how to interpret the content.
94
+ *
95
+ * @default "text/plain"
96
+ * @example "text/markdown"
97
+ * @example "application/json"
98
+ */
99
+ mimeType?: string;
100
+
101
+ /**
102
+ * Handler function that returns the resource content.
103
+ *
104
+ * Called when the resource is read. Can return text or binary content.
105
+ *
106
+ * @returns Resource content with either `text` or `blob` property
107
+ */
108
+ handler: ResourceHandler;
109
+ }
110
+
111
+ // ---------------------------------------------------------------------------------------------------------------------
112
+
113
+ export class ResourcePrimitive extends Primitive<ResourcePrimitiveOptions> {
114
+ protected readonly mcpServer = $inject(McpServerProvider);
115
+
116
+ /**
117
+ * Returns the name of the resource.
118
+ */
119
+ public get name(): string {
120
+ return this.options.name ?? this.config.propertyKey;
121
+ }
122
+
123
+ /**
124
+ * Returns the URI of the resource.
125
+ */
126
+ public get uri(): string {
127
+ return this.options.uri;
128
+ }
129
+
130
+ /**
131
+ * Returns the description of the resource.
132
+ */
133
+ public get description(): string | undefined {
134
+ return this.options.description;
135
+ }
136
+
137
+ /**
138
+ * Returns the MIME type of the resource.
139
+ */
140
+ public get mimeType(): string {
141
+ return this.options.mimeType ?? "text/plain";
142
+ }
143
+
144
+ protected onInit(): void {
145
+ this.mcpServer.registerResource(this);
146
+ }
147
+
148
+ /**
149
+ * Read the resource content.
150
+ *
151
+ * @param context - Optional context from the transport layer
152
+ * @returns The resource content
153
+ */
154
+ public async read(context?: McpContext): Promise<ResourceContent> {
155
+ return this.options.handler({ context });
156
+ }
157
+
158
+ /**
159
+ * Convert the resource to an MCP resource descriptor for protocol messages.
160
+ */
161
+ public toDescriptor(): McpResourceDescriptor {
162
+ return {
163
+ uri: this.uri,
164
+ name: this.name,
165
+ description: this.description,
166
+ mimeType: this.mimeType,
167
+ };
168
+ }
169
+ }
170
+
171
+ $resource[KIND] = ResourcePrimitive;
@@ -0,0 +1,285 @@
1
+ import {
2
+ $inject,
3
+ type Async,
4
+ createPrimitive,
5
+ KIND,
6
+ Primitive,
7
+ type TObject,
8
+ type TSchema,
9
+ t,
10
+ } from "alepha";
11
+ import type {
12
+ McpContext,
13
+ McpJsonSchema,
14
+ McpToolDescriptor,
15
+ ToolHandlerArgs,
16
+ ToolHandlerResult,
17
+ ToolPrimitiveSchema,
18
+ } from "../interfaces/McpTypes.ts";
19
+ import { McpServerProvider } from "../providers/McpServerProvider.ts";
20
+
21
+ // ---------------------------------------------------------------------------------------------------------------------
22
+
23
+ /**
24
+ * Creates an MCP tool primitive for defining callable functions.
25
+ *
26
+ * Tools are the primary way for LLMs to interact with external systems through MCP.
27
+ * Each tool has a name, description, typed parameters, and a handler function.
28
+ *
29
+ * **Key Features**
30
+ * - Full TypeScript inference for parameters and results
31
+ * - Automatic schema validation using TypeBox
32
+ * - JSON Schema generation for MCP protocol
33
+ * - Integration with MCP server provider
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * class CalculatorTools {
38
+ * add = $tool({
39
+ * description: "Add two numbers together",
40
+ * schema: {
41
+ * params: t.object({
42
+ * a: t.number(),
43
+ * b: t.number(),
44
+ * }),
45
+ * result: t.number(),
46
+ * },
47
+ * handler: async ({ params }) => {
48
+ * return params.a + params.b;
49
+ * },
50
+ * });
51
+ *
52
+ * greet = $tool({
53
+ * description: "Generate a greeting message",
54
+ * schema: {
55
+ * params: t.object({
56
+ * name: t.text(),
57
+ * }),
58
+ * result: t.text(),
59
+ * },
60
+ * handler: async ({ params }) => {
61
+ * return `Hello, ${params.name}!`;
62
+ * },
63
+ * });
64
+ * }
65
+ * ```
66
+ */
67
+ export const $tool = <T extends ToolPrimitiveSchema>(
68
+ options: ToolPrimitiveOptions<T>,
69
+ ): ToolPrimitive<T> => {
70
+ return createPrimitive(ToolPrimitive<T>, options);
71
+ };
72
+
73
+ // ---------------------------------------------------------------------------------------------------------------------
74
+
75
+ export interface ToolPrimitiveOptions<T extends ToolPrimitiveSchema> {
76
+ /**
77
+ * The name of the tool.
78
+ *
79
+ * If not provided, defaults to the property key where the tool is declared.
80
+ * Names should be descriptive and use kebab-case or snake_case.
81
+ *
82
+ * @example "calculate-sum"
83
+ * @example "get_weather"
84
+ */
85
+ name?: string;
86
+
87
+ /**
88
+ * A human-readable description of what the tool does.
89
+ *
90
+ * This description is sent to the LLM to help it understand
91
+ * when and how to use the tool. Be clear and specific.
92
+ *
93
+ * @example "Calculate the sum of two numbers"
94
+ * @example "Retrieve current weather data for a given location"
95
+ */
96
+ description: string;
97
+
98
+ /**
99
+ * TypeBox schema defining the tool's parameters and result type.
100
+ *
101
+ * - **params**: TObject schema for input parameters (optional)
102
+ * - **result**: TSchema for the return value (optional)
103
+ *
104
+ * Schemas provide:
105
+ * - Type inference for handler function
106
+ * - Runtime validation of inputs
107
+ * - JSON Schema generation for MCP protocol
108
+ */
109
+ schema?: T;
110
+
111
+ /**
112
+ * The handler function that executes when the tool is called.
113
+ *
114
+ * Receives validated parameters and returns the result.
115
+ * Errors thrown here are caught and returned as MCP errors.
116
+ *
117
+ * @param args - Object containing validated params
118
+ * @returns The tool result (can be async)
119
+ */
120
+ handler: (args: ToolHandlerArgs<T>) => Async<ToolHandlerResult<T>>;
121
+ }
122
+
123
+ // ---------------------------------------------------------------------------------------------------------------------
124
+
125
+ export class ToolPrimitive<T extends ToolPrimitiveSchema> extends Primitive<
126
+ ToolPrimitiveOptions<T>
127
+ > {
128
+ protected readonly mcpServer = $inject(McpServerProvider);
129
+
130
+ /**
131
+ * Returns the name of the tool.
132
+ */
133
+ public get name(): string {
134
+ return this.options.name ?? this.config.propertyKey;
135
+ }
136
+
137
+ /**
138
+ * Returns the description of the tool.
139
+ */
140
+ public get description(): string {
141
+ return this.options.description;
142
+ }
143
+
144
+ protected onInit(): void {
145
+ this.mcpServer.registerTool(this);
146
+ }
147
+
148
+ /**
149
+ * Execute the tool with the given parameters.
150
+ *
151
+ * @param params - Raw parameters to validate and pass to the handler
152
+ * @param context - Optional context from the transport layer
153
+ * @returns The tool result
154
+ */
155
+ public async execute(
156
+ params: unknown,
157
+ context?: McpContext,
158
+ ): Promise<ToolHandlerResult<T>> {
159
+ let validatedParams: any = params ?? {};
160
+
161
+ // Validate params using alepha.codec if schema provided
162
+ if (this.options.schema?.params) {
163
+ validatedParams = this.alepha.codec.decode(
164
+ this.options.schema.params,
165
+ validatedParams,
166
+ );
167
+ }
168
+
169
+ const result = await this.options.handler({
170
+ params: validatedParams,
171
+ context,
172
+ });
173
+
174
+ // Validate and encode result if schema provided
175
+ if (this.options.schema?.result && result !== undefined) {
176
+ return this.alepha.codec.encode(
177
+ this.options.schema.result,
178
+ result,
179
+ ) as ToolHandlerResult<T>;
180
+ }
181
+
182
+ return result as ToolHandlerResult<T>;
183
+ }
184
+
185
+ /**
186
+ * Convert the tool to an MCP tool descriptor for protocol messages.
187
+ */
188
+ public toDescriptor(): McpToolDescriptor {
189
+ return {
190
+ name: this.name,
191
+ description: this.description,
192
+ inputSchema: this.options.schema?.params
193
+ ? this.schemaToJsonSchema(this.options.schema.params)
194
+ : { type: "object", properties: {}, required: [] },
195
+ };
196
+ }
197
+
198
+ /**
199
+ * Convert a TypeBox schema to JSON Schema format.
200
+ */
201
+ protected schemaToJsonSchema(schema: TObject): McpJsonSchema {
202
+ const properties: Record<string, unknown> = {};
203
+ const required: string[] = [];
204
+
205
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
206
+ properties[key] = this.propertyToJsonSchema(propSchema as TSchema);
207
+
208
+ // Check if property is required (not optional)
209
+ if (!t.schema.isOptional(propSchema as TSchema)) {
210
+ required.push(key);
211
+ }
212
+ }
213
+
214
+ return {
215
+ type: "object",
216
+ properties,
217
+ required,
218
+ };
219
+ }
220
+
221
+ /**
222
+ * Convert a single property schema to JSON Schema format.
223
+ */
224
+ protected propertyToJsonSchema(schema: TSchema): Record<string, unknown> {
225
+ const result: Record<string, unknown> = {};
226
+
227
+ // Check for description on all types
228
+ if ("description" in schema) {
229
+ result.description = schema.description;
230
+ }
231
+
232
+ if (t.schema.isString(schema)) {
233
+ result.type = "string";
234
+ if ("minLength" in schema) result.minLength = schema.minLength;
235
+ if ("maxLength" in schema) result.maxLength = schema.maxLength;
236
+ if ("pattern" in schema) result.pattern = schema.pattern;
237
+ if ("enum" in schema) result.enum = schema.enum;
238
+ } else if (t.schema.isNumber(schema)) {
239
+ result.type = "number";
240
+ if ("minimum" in schema) result.minimum = schema.minimum;
241
+ if ("maximum" in schema) result.maximum = schema.maximum;
242
+ } else if (t.schema.isInteger(schema)) {
243
+ result.type = "integer";
244
+ if ("minimum" in schema) result.minimum = schema.minimum;
245
+ if ("maximum" in schema) result.maximum = schema.maximum;
246
+ } else if (t.schema.isBoolean(schema)) {
247
+ result.type = "boolean";
248
+ } else if (t.schema.isArray(schema)) {
249
+ result.type = "array";
250
+ if ("items" in schema) {
251
+ result.items = this.propertyToJsonSchema(schema.items as TSchema);
252
+ }
253
+ } else if (t.schema.isObject(schema)) {
254
+ Object.assign(result, this.schemaToJsonSchema(schema));
255
+ } else if (t.schema.isUnsafe(schema) || t.schema.isOptional(schema)) {
256
+ // Handle Unsafe types (like t.enum) and optional wrappers by checking the underlying type property
257
+ const schemaAny = schema as { type?: string; enum?: unknown[] };
258
+ if (schemaAny.type === "string") {
259
+ result.type = "string";
260
+ if ("enum" in schema) result.enum = schema.enum;
261
+ if ("pattern" in schema) result.pattern = schema.pattern;
262
+ } else if (schemaAny.type === "number") {
263
+ result.type = "number";
264
+ } else if (schemaAny.type === "integer") {
265
+ result.type = "integer";
266
+ } else if (schemaAny.type === "boolean") {
267
+ result.type = "boolean";
268
+ } else if (schemaAny.type === "array") {
269
+ result.type = "array";
270
+ } else if (schemaAny.type === "object") {
271
+ result.type = "object";
272
+ } else {
273
+ // Fallback
274
+ result.type = "string";
275
+ }
276
+ } else {
277
+ // Fallback for other types
278
+ result.type = "string";
279
+ }
280
+
281
+ return result;
282
+ }
283
+ }
284
+
285
+ $tool[KIND] = ToolPrimitive;