@lunora/mcp 1.0.0-alpha.7 → 1.0.0-alpha.71

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 (29) hide show
  1. package/LICENSE.md +126 -0
  2. package/README.md +139 -9
  3. package/dist/bin.mjs +3 -35
  4. package/dist/docs/index.d.mts +250 -0
  5. package/dist/docs/index.d.ts +250 -0
  6. package/dist/docs/index.mjs +1 -0
  7. package/dist/index.d.mts +355 -14
  8. package/dist/index.d.ts +355 -14
  9. package/dist/index.mjs +1 -2
  10. package/dist/packem_shared/AGENT_RUN_INPUT_SCHEMA-DRSY74ed.mjs +1 -0
  11. package/dist/packem_shared/DEFAULT_DOCS_BASE_URL-CZ3fVsSc.mjs +4 -0
  12. package/dist/packem_shared/DEFAULT_SEARCH_LIMIT-DWPt0hvR.mjs +3 -0
  13. package/dist/packem_shared/DOCS_SERVER_NAME-BWzPxJyZ.mjs +1 -0
  14. package/dist/packem_shared/DOCS_URI_SCHEME-CFANc3vr.mjs +3 -0
  15. package/dist/packem_shared/LOCAL_SERVER_NAME-0Jb4neqA.mjs +1 -0
  16. package/dist/packem_shared/OBSERVABILITY_TOOL_DEFINITIONS-KrCukPbu.mjs +1 -0
  17. package/dist/packem_shared/READ_ONLY_TOOL_DEFINITIONS-DGexf3Tn.mjs +1 -0
  18. package/dist/packem_shared/connectStdio-BCeI0Wqu.mjs +1 -0
  19. package/dist/packem_shared/createMcpFetchHandler-TKDnZTGs.mjs +1 -0
  20. package/dist/packem_shared/createPaidMcpServer-CQO-59WV.mjs +1 -0
  21. package/dist/packem_shared/createToolServer-BtGuPyMU.mjs +1 -0
  22. package/dist/packem_shared/observability-tools-Ce0YK58T.mjs +1 -0
  23. package/dist/packem_shared/serve-stateless.d-B_q8q39X.d.mts +133 -0
  24. package/dist/packem_shared/serve-stateless.d-B_q8q39X.d.ts +133 -0
  25. package/dist/packem_shared/serveStateless-Db7J3pAO.mjs +1 -0
  26. package/dist/packem_shared/toDocsSearchHits-CBLmtWXt.mjs +1 -0
  27. package/package.json +17 -3
  28. package/dist/packem_shared/TOOL_DEFINITIONS-Dpiu38ji.mjs +0 -112
  29. package/dist/packem_shared/connectStdio-C_mvQBs2.mjs +0 -64
package/dist/index.d.ts CHANGED
@@ -1,30 +1,371 @@
1
1
  import { LunoraClient } from '@lunora/client';
2
+ import { T as ToolDefinition, f as ToolResult, e as ToolInputSchema, a as McpFetchHandler, b as McpTool } from "./packem_shared/serve-stateless.d-B_q8q39X.js";
3
+ export { type d as McpServerInfo, g as createToolServer, s as serveStateless } from "./packem_shared/serve-stateless.d-B_q8q39X.js";
2
4
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
5
+ import { Tool } from '@modelcontextprotocol/sdk/types.js';
6
+ import '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
7
+ /**
8
+ * The observability tools. Descriptions say WHEN to call the tool, not just
9
+ * what it returns — an agent picking between five similar reads needs the
10
+ * trigger, and it pays for these strings on every turn.
11
+ */
12
+ declare const OBSERVABILITY_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
13
+ /** The read-only tool surface: introspection + query. Always exposed. */
14
+ declare const READ_ONLY_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
15
+ /** The write tool surface (mutations + actions). Exposed ONLY when writes are enabled. */
16
+ declare const WRITE_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
17
+ /**
18
+ * The tools this server advertises, in three tiers:
19
+ *
20
+ * - the read-only surface, always exposed;
21
+ * - the observability surface, exposed only when an admin token resolved —
22
+ * read-only, but it surfaces production logs and grouped errors, so an
23
+ * unauthenticated server must not even advertise that it exists;
24
+ * - the write surface, exposed only when `allowWrites` is set.
25
+ *
26
+ * Both gates OMIT rather than refuse: an AI agent can't invoke what it can't
27
+ * see. Dispatch re-checks both in {@link callTool}, so the guarantee does not
28
+ * depend on a client honouring the advertised list.
29
+ */
30
+ declare const toolDefinitions: (allowWrites: boolean, hasAdminToken?: boolean) => ReadonlyArray<ToolDefinition>;
31
+ /**
32
+ * Dispatch a tool call against `client`. Unknown tools and thrown errors are
33
+ * returned as `isError` results (rather than rejections) so the calling model
34
+ * sees the failure as tool output, per the MCP convention.
35
+ *
36
+ * `allowWrites` gates the mutation/action tools and `hasAdminToken` gates the
37
+ * observability tools: when either is false a call to the gated tool is refused
38
+ * even if the client somehow names it, so both guarantees hold at dispatch, not
39
+ * just in the advertised tool list.
40
+ */
41
+ declare const callTool: (client: LunoraClient, name: string, input: Record<string, unknown>, allowWrites?: boolean, hasAdminToken?: boolean) => Promise<ToolResult>;
42
+ /**
43
+ * Agent exposure for the MCP server: a durable `@lunora/agent` run fronted as an
44
+ * MCP tool an external agent can call. The capability boundary is the MCP-server
45
+ * process + its token, so WHICH agents are exposed is config on the server (like
46
+ * `allowWrites`), not on `defineAgent` — keeping `@lunora/agent` codegen
47
+ * byte-identical.
48
+ */
49
+ interface McpAgentExposure {
50
+ /** What the agent does — shown to the calling model, which decides from it. */
51
+ description: string;
52
+ /** The agent's export name (its `ctx.agents.<name>` / `AGENT_<NAME>` binding). */
53
+ name: string;
54
+ /** Override the model-facing tool name (default `agent_<name>`). */
55
+ toolName?: string;
56
+ }
57
+ /** The generic status/poll tool advertised alongside the per-agent tools. */
58
+ declare const AGENT_STATUS_TOOL_NAME = "lunora_agent_status";
59
+ /**
60
+ * The uniform input schema every agent tool advertises. Agents share ONE run
61
+ * input (`@lunora/agent` has no per-agent validator), so there is nothing to
62
+ * derive per agent — a single static schema is reused for every agent tool.
63
+ */
64
+ declare const AGENT_RUN_INPUT_SCHEMA: ToolInputSchema;
65
+ /**
66
+ * Parse `LUNORA_MCP_AGENTS` — a `;`-separated list of `name:description` pairs,
67
+ * e.g. `"support:Handles support questions;billing:Billing help"`. The
68
+ * description may itself contain colons (only the FIRST colon splits). Blank
69
+ * entries and entries with an empty name/description are skipped.
70
+ */
71
+ declare const parseAgentsEnv: (raw: string | undefined) => McpAgentExposure[];
72
+ /**
73
+ * The tools this module advertises. Fail-closed: only the boolean `true` opts
74
+ * in (an env-plumbed caller could pass a truthy string), and the tools appear
75
+ * ONLY when at least one agent is exposed — so an agent-free or non-opted-in
76
+ * server never lists them.
77
+ */
78
+ declare const agentToolDefinitions: (exposures: ReadonlyArray<McpAgentExposure>, allowAgents: boolean) => ReadonlyArray<ToolDefinition>;
79
+ /** Options threaded into a single agent tool dispatch. */
80
+ interface CallAgentToolOptions {
81
+ /** Opt-in gate — must be exactly `true` or the call is refused fail-closed. */
82
+ allowAgents: boolean;
83
+ /** The exposures advertised by this server. */
84
+ exposures: ReadonlyArray<McpAgentExposure>;
85
+ /** Wall-clock budget a single call awaits before returning a pending result. */
86
+ maxWaitMs?: number;
87
+ /** Delay between thread-status polls. */
88
+ pollIntervalMs?: number;
89
+ /** Test seam replacing the between-poll wait; production uses a real timer. */
90
+ wait?: (ms: number) => Promise<void>;
91
+ }
92
+ /**
93
+ * Dispatch an agent tool call: start a durable run via `agents:agentRun`, then
94
+ * await-with-timeout — poll `agents:agentThread` until terminal (returning the
95
+ * final answer from `agents:agentMessages`) or, on budget exhaustion, return a
96
+ * NON-error pending payload the caller resumes with `lunora_agent_status`.
97
+ *
98
+ * Fail-closed: refused at dispatch unless `allowAgents === true`, mirroring the
99
+ * `allowWrites` guard — starting a run is a side effect and must not ride the
100
+ * read-only default.
101
+ */
102
+ declare const callAgentTool: (client: LunoraClient, name: string, input: Record<string, unknown>, options: CallAgentToolOptions) => Promise<ToolResult>;
3
103
  interface LunoraMcpServerOptions {
104
+ /** Wall-clock budget a single agent tool call awaits before returning a pending result. */
105
+ agentMaxWaitMs?: number;
106
+ /** Delay between agent thread-status polls. */
107
+ agentPollIntervalMs?: number;
108
+ /** The agents this server fronts as MCP tools (see `allowAgents`). */
109
+ agents?: ReadonlyArray<McpAgentExposure>;
110
+ /**
111
+ * Expose the per-agent tools (`agent_<name>` + the generic
112
+ * `lunora_agent_status`). Defaults to `false`, mirroring `allowWrites`:
113
+ * starting a durable agent run is a side effect, so the agent tools are
114
+ * omitted from the advertised list AND refused at dispatch unless explicitly
115
+ * opted in. Only takes effect together with a non-empty `agents` list.
116
+ */
117
+ allowAgents?: boolean;
118
+ /**
119
+ * Expose the write tools (`lunora_run_mutation` / `lunora_run_action`).
120
+ * Defaults to `false`: the server is READ-ONLY unless explicitly opted in,
121
+ * so a prompt-injected or misaligned agent can't mutate the deployment with
122
+ * the configured token. When false the write tools are omitted from the
123
+ * advertised tool list AND refused at dispatch.
124
+ */
125
+ allowWrites?: boolean;
126
+ /**
127
+ * Pre-built client (test injection). When omitted a `LunoraClient` is
128
+ * created from `url`/`token`/`fetch`.
129
+ */
4
130
  client?: LunoraClient;
131
+ /** `fetch` implementation; defaults to the ambient global. */
5
132
  fetch?: typeof fetch;
133
+ /**
134
+ * Bearer token sent on every RPC. This must be the deployment's **admin
135
+ * bearer**: the introspection/allowlist path every tool depends on
136
+ * (`lunora_list_functions`, `lunora_list_tables`, and the `assertRunnable`
137
+ * precheck that runs before every `run` tool) hits admin-gated
138
+ * `/_lunora/admin/*` routes, so no scoped/app token works today — it would
139
+ * 403 (`ADMIN_FORBIDDEN`) on the first tool call. The read-only guarantee is
140
+ * therefore NOT enforced by the token's scope; it is enforced in-process via
141
+ * `allowWrites: false` (the default), which omits the write tools from the
142
+ * advertised list and refuses them at dispatch.
143
+ *
144
+ * Its presence is also what gates the observability tools (logs, Issues,
145
+ * advisories, query insights, migration status): without a token they are
146
+ * omitted from `ListTools` and refused at dispatch.
147
+ */
6
148
  token?: string;
149
+ /** Base URL of the deployed Lunora Worker. Required unless `client` is given. */
7
150
  url?: string;
8
151
  }
152
+ /**
153
+ * Build an MCP `Server` whose tools talk to a Lunora deployment. The server is
154
+ * transport-agnostic — call `.connect(transport)` yourself, or use
155
+ * `connectStdio` for the common stdio case.
156
+ *
157
+ * Tool calls are dispatched through `callTool`, which the deployment reaches
158
+ * over HTTP RPC. No WebSocket is opened (the tools never subscribe), so this is
159
+ * safe to run as a short-lived stdio process.
160
+ */
9
161
  declare const createLunoraMcpServer: (options: LunoraMcpServerOptions) => Server;
162
+ /**
163
+ * Build the server and connect it over stdio — the transport MCP clients use
164
+ * when they spawn the `lunora-mcp` binary. Resolves once the transport is
165
+ * connected; the process then stays alive serving requests.
166
+ */
10
167
  declare const connectStdio: (options: LunoraMcpServerOptions) => Promise<Server>;
11
- interface ToolInputSchema {
12
- properties: Record<string, unknown>;
13
- required?: ReadonlyArray<string>;
14
- type: "object";
168
+ /**
169
+ * Build a stateless Streamable-HTTP fetch handler for a Lunora MCP server. Each
170
+ * invocation constructs a fresh proxy server and serves the request through
171
+ * {@link serveStateless}.
172
+ */
173
+ declare const createMcpFetchHandler: (options: LunoraMcpServerOptions) => McpFetchHandler;
174
+ /** A Lunora deployment the tools dispatch against. */
175
+ interface LocalDeployment {
176
+ token?: string;
177
+ url: string;
15
178
  }
16
- interface ToolDefinition {
179
+ /**
180
+ * Where the deployment comes from: a fixed value, or a function consulted on
181
+ * every tool call.
182
+ *
183
+ * The resolver form exists because an editor spawns this server when the
184
+ * project opens — routinely *before* `lunora dev` is running, and it keeps the
185
+ * process alive across every restart afterwards. A URL captured once at startup
186
+ * would therefore be absent for the entire first session and stale after the
187
+ * first restart.
188
+ */
189
+ type LocalDeploymentSource = (() => LocalDeployment | undefined) | LocalDeployment;
190
+ interface LocalMcpServerOptions {
191
+ /**
192
+ * Expose the deployment write tools (`lunora_run_mutation` /
193
+ * `lunora_run_action`). Defaults to `false` — the same fail-closed default
194
+ * as the remote server. Locally the blast radius is dev data rather than
195
+ * production, but a mutation is still a side effect an agent should be
196
+ * granted deliberately.
197
+ */
198
+ allowWrites?: boolean;
199
+ /**
200
+ * The Lunora deployment (usually the running dev server) to expose. Omit to
201
+ * leave the deployment tools out entirely.
202
+ */
203
+ deployment?: LocalDeploymentSource;
204
+ /** Docs site origin backing the documentation tools; `false` omits them. */
205
+ docs?: false | {
206
+ baseUrl?: string;
207
+ };
208
+ /** Extra tools to compose in, e.g. the CLI's local dev-server tools. */
209
+ extraTools?: ReadonlyArray<McpTool>;
210
+ /** `fetch` implementation; defaults to the ambient global. */
211
+ fetch?: typeof fetch;
212
+ /** Version reported in the MCP handshake — the host CLI's, not this package's. */
213
+ version?: string;
214
+ }
215
+ /** Server identity advertised in the MCP `initialize` handshake. */
216
+ declare const LOCAL_SERVER_NAME = "lunora";
217
+ /** Shown when a deployment tool is called and no dev server can be found. */
218
+ declare const NO_DEPLOYMENT_MESSAGE = "no Lunora dev server is running for this project — start one with `lunora dev`, then call this tool again (call lunora_dev_status to check).";
219
+ /**
220
+ * Assemble the tool list, in the order it is advertised: docs first (the
221
+ * surface that always works), then the caller's extras, then the deployment
222
+ * tools. Order also decides precedence — `createToolServer` keeps the first
223
+ * registration of a duplicated name.
224
+ *
225
+ * `clientFor` is the shared client cache built once by
226
+ * {@link createLocalMcpServer} and threaded into both the tool and resource
227
+ * surfaces. Exported (and called directly by tests) without going through
228
+ * `createLocalMcpServer`, so a caller that omits it gets a private,
229
+ * call-scoped cache — same shape as before this surface was shared, just
230
+ * without the cross-surface sharing that only matters once a resource
231
+ * surface exists alongside it.
232
+ */
233
+ declare const localTools: (options: LocalMcpServerOptions, clientFor?: (deployment: LocalDeployment) => LunoraClient) => ReadonlyArray<McpTool>;
234
+ /** Build the composed local server without connecting a transport. */
235
+ declare const createLocalMcpServer: (options?: LocalMcpServerOptions) => Server;
236
+ /**
237
+ * Build the composed local server and connect it over stdio — the transport an
238
+ * MCP client uses when it spawns `lunora mcp serve`. Resolves once connected;
239
+ * the process then stays alive serving requests.
240
+ */
241
+ declare const connectLocalStdio: (options?: LocalMcpServerOptions) => Promise<Server>;
242
+ /** A tool handler: receives the call's `arguments` bag, returns an MCP tool result. */
243
+ /**
244
+ * The x402 vocabulary this module needs, declared here rather than imported.
245
+ *
246
+ * The x402 package is an optional peer, and a type import from its `charge`
247
+ * entry puts its `.d.ts` back into this package's build graph:
248
+ * a consumer that never installs x402 never builds it either, so the dts bundler
249
+ * looks for a `dist/` that does not exist and fails. That is not hypothetical —
250
+ * it broke the docs site build, which runs a filtered build over the docs app and its dependency closure
251
+ * and therefore never builds x402.
252
+ *
253
+ * Declaring them locally is safe because this module never *inspects* a charge
254
+ * config; it forwards it whole to `createChargeMiddleware`. The index signature
255
+ * keeps a real charge config assignable as x402 grows fields.
256
+ */
257
+ /** Mirrors x402's `X402Price` — a decimal string like `"$0.05"`, or a number. */
258
+ type X402Price = number | string;
259
+ /** Mirrors x402's charge config with the per-tool price omitted. */
260
+ interface X402ChargeSettings {
261
+ /** Network this resource settles on. */
262
+ readonly network: string;
263
+ /** Everything else x402 accepts, forwarded untouched. */
264
+ readonly [key: string]: unknown;
265
+ /** Payout wallet(s), per network family. */
266
+ readonly recipient: {
267
+ readonly evm?: string;
268
+ readonly svm?: string;
269
+ };
270
+ }
271
+ type ToolHandler = (arguments_: Record<string, unknown>) => Promise<ToolResult> | ToolResult;
272
+ /** Registration shape for a free tool. */
273
+ interface RegisterToolOptions {
274
+ /** Optional MCP tool annotations (`readOnlyHint`, `title`, …). */
275
+ annotations?: Tool["annotations"];
276
+ /** Human/model-facing description of what the tool does. */
17
277
  description: string;
278
+ /** JSON-Schema object describing the tool's arguments. */
18
279
  inputSchema: ToolInputSchema;
280
+ /** Unique tool name (the MCP `tools/call` `name`). */
19
281
  name: string;
20
282
  }
21
- interface ToolResult {
22
- content: {
23
- text: string;
24
- type: "text";
25
- }[];
26
- isError?: boolean;
283
+ /** Registration shape for a paid tool: a {@link RegisterToolOptions} plus its USD price. */
284
+ interface RegisterPaidToolOptions extends RegisterToolOptions {
285
+ /** USD price per call (e.g. `"$0.05"`), charged via x402 before dispatch. */
286
+ price: X402Price;
287
+ }
288
+ /** x402 settlement vocabulary shared by every paid tool (network, recipient, facilitator); price is per-tool. */
289
+ type PaidMcpChargeConfig = X402ChargeSettings;
290
+ /** Config for `createPaidMcpServer`. */
291
+ interface PaidMcpServerConfig {
292
+ /** The worker-level x402 charge config; each paid tool supplies only its own `price`. */
293
+ charge: PaidMcpChargeConfig;
294
+ /** Name/version advertised in the MCP `initialize` handshake. Defaults to `lunora-paid-mcp`. */
295
+ serverInfo?: {
296
+ name: string;
297
+ version: string;
298
+ };
299
+ }
300
+ /** A paid MCP server: register free/paid tools, then serve over Streamable HTTP. */
301
+ interface PaidMcpServer {
302
+ /** The Streamable-HTTP fetch handler; gates each paid `tools/call` behind x402. */
303
+ readonly fetchHandler: McpFetchHandler;
304
+ /** Register a **paid** tool: its dispatch runs the x402 charge middleware first. */
305
+ paidTool: (options: RegisterPaidToolOptions, handler: ToolHandler) => void;
306
+ /** Register a **free** tool (coexists with paid tools on the same server). */
307
+ tool: (options: RegisterToolOptions, handler: ToolHandler) => void;
27
308
  }
28
- declare const TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
29
- declare const callTool: (client: LunoraClient, name: string, input: Record<string, unknown>) => Promise<ToolResult>;
30
- export { type LunoraMcpServerOptions, TOOL_DEFINITIONS, type ToolDefinition, type ToolInputSchema, type ToolResult, callTool, connectStdio, createLunoraMcpServer };
309
+ /**
310
+ * Create a paid MCP server. Register free tools with `tool()` and priced tools
311
+ * with `paidTool()` (they coexist), then serve `fetchHandler` over HTTP.
312
+ *
313
+ * The server is **stateless**: `fetchHandler` builds a fresh `Server` per
314
+ * request (reading the live tool registry), so tools registered before the
315
+ * first request are all visible. Each priced tool memoises one initialised
316
+ * `ChargeMiddleware` (keyed by tool name, baking that tool's price and naming
317
+ * the tool as the challenge `resource`); a failed init is not cached, so a
318
+ * transient facilitator outage retries on the next call.
319
+ */
320
+ declare const createPaidMcpServer: (config: PaidMcpServerConfig) => PaidMcpServer;
321
+ export { AGENT_RUN_INPUT_SCHEMA, AGENT_STATUS_TOOL_NAME,
322
+ /**
323
+ * `@lunora/mcp` — Model Context Protocol servers for Lunora. This entry exposes
324
+ * a *deployment* to AI agents; the `@lunora/mcp/docs` subpath exposes the
325
+ * framework's *documentation* (credential-free, and safe to host publicly).
326
+ *
327
+ * The deployment server: It registers tools for introspecting a deployment
328
+ * (`lunora_list_functions`, `lunora_list_tables`) and invoking its functions
329
+ * (`lunora_run_query`, plus `lunora_run_mutation` and `lunora_run_action` when
330
+ * writes are enabled), each backed by `LunoraClient` over HTTP RPC. It also
331
+ * exposes the deployment's observability reads (`lunora_get_logs`,
332
+ * `lunora_get_issues`, `lunora_get_advisories`, `lunora_get_query_insights`,
333
+ * `lunora_get_migration_status`) whenever an admin token resolved — read-only,
334
+ * but privileged, so they are omitted entirely without one. The server is
335
+ * read-only by default — the write tools are exposed only when `allowWrites`
336
+ * (or the `LUNORA_MCP_ALLOW_WRITES` env) is set, and every run tool is
337
+ * allowlisted against the deployment's discovered public functions. It can also
338
+ * front durable `@lunora/agent` runs as `agent_<name>` tools when `allowAgents`
339
+ * (or `LUNORA_MCP_ALLOW_AGENTS` + `LUNORA_MCP_AGENTS`) is set. Run the
340
+ * `lunora-mcp` binary (configured via the `LUNORA_URL`, `LUNORA_ADMIN_TOKEN`,
341
+ * and `LUNORA_MCP_ALLOW_WRITES` env vars) for the stdio transport, serve the
342
+ * server remotely over Streamable HTTP with `createMcpFetchHandler` (a
343
+ * Workers-ready `Request` → `Response` handler), or build a server
344
+ * programmatically with `createLunoraMcpServer` and connect any transport.
345
+ */
346
+ type CallAgentToolOptions, LOCAL_SERVER_NAME, type LocalDeployment, type LocalDeploymentSource, type LocalMcpServerOptions, type LunoraMcpServerOptions,
347
+ /**
348
+ * `@lunora/mcp` — Model Context Protocol servers for Lunora. This entry exposes
349
+ * a *deployment* to AI agents; the `@lunora/mcp/docs` subpath exposes the
350
+ * framework's *documentation* (credential-free, and safe to host publicly).
351
+ *
352
+ * The deployment server: It registers tools for introspecting a deployment
353
+ * (`lunora_list_functions`, `lunora_list_tables`) and invoking its functions
354
+ * (`lunora_run_query`, plus `lunora_run_mutation` and `lunora_run_action` when
355
+ * writes are enabled), each backed by `LunoraClient` over HTTP RPC. It also
356
+ * exposes the deployment's observability reads (`lunora_get_logs`,
357
+ * `lunora_get_issues`, `lunora_get_advisories`, `lunora_get_query_insights`,
358
+ * `lunora_get_migration_status`) whenever an admin token resolved — read-only,
359
+ * but privileged, so they are omitted entirely without one. The server is
360
+ * read-only by default — the write tools are exposed only when `allowWrites`
361
+ * (or the `LUNORA_MCP_ALLOW_WRITES` env) is set, and every run tool is
362
+ * allowlisted against the deployment's discovered public functions. It can also
363
+ * front durable `@lunora/agent` runs as `agent_<name>` tools when `allowAgents`
364
+ * (or `LUNORA_MCP_ALLOW_AGENTS` + `LUNORA_MCP_AGENTS`) is set. Run the
365
+ * `lunora-mcp` binary (configured via the `LUNORA_URL`, `LUNORA_ADMIN_TOKEN`,
366
+ * and `LUNORA_MCP_ALLOW_WRITES` env vars) for the stdio transport, serve the
367
+ * server remotely over Streamable HTTP with `createMcpFetchHandler` (a
368
+ * Workers-ready `Request` → `Response` handler), or build a server
369
+ * programmatically with `createLunoraMcpServer` and connect any transport.
370
+ */
371
+ type McpAgentExposure, type McpFetchHandler, type McpTool, NO_DEPLOYMENT_MESSAGE, OBSERVABILITY_TOOL_DEFINITIONS, type PaidMcpChargeConfig, type PaidMcpServer, type PaidMcpServerConfig, READ_ONLY_TOOL_DEFINITIONS, type RegisterPaidToolOptions, type RegisterToolOptions, type ToolDefinition, type ToolHandler, type ToolInputSchema, type ToolResult, WRITE_TOOL_DEFINITIONS, agentToolDefinitions, callAgentTool, callTool, connectLocalStdio, connectStdio, createLocalMcpServer, createLunoraMcpServer, createMcpFetchHandler, createPaidMcpServer, localTools, parseAgentsEnv, toolDefinitions };
package/dist/index.mjs CHANGED
@@ -1,2 +1 @@
1
- export { connectStdio, createLunoraMcpServer } from './packem_shared/connectStdio-C_mvQBs2.mjs';
2
- export { TOOL_DEFINITIONS, callTool } from './packem_shared/TOOL_DEFINITIONS-Dpiu38ji.mjs';
1
+ import{AGENT_RUN_INPUT_SCHEMA as r,AGENT_STATUS_TOOL_NAME as t,agentToolDefinitions as T,callAgentTool as c,parseAgentsEnv as E}from"./packem_shared/AGENT_RUN_INPUT_SCHEMA-DRSY74ed.mjs";import{createToolServer as O}from"./packem_shared/createToolServer-BtGuPyMU.mjs";import{createMcpFetchHandler as _}from"./packem_shared/createMcpFetchHandler-TKDnZTGs.mjs";import{LOCAL_SERVER_NAME as N,NO_DEPLOYMENT_MESSAGE as n,connectLocalStdio as p,createLocalMcpServer as I,localTools as A}from"./packem_shared/LOCAL_SERVER_NAME-0Jb4neqA.mjs";import{createPaidMcpServer as f}from"./packem_shared/createPaidMcpServer-CQO-59WV.mjs";import{connectStdio as m,createLunoraMcpServer as s}from"./packem_shared/connectStdio-BCeI0Wqu.mjs";import{READ_ONLY_TOOL_DEFINITIONS as M,WRITE_TOOL_DEFINITIONS as D,callTool as v,toolDefinitions as R}from"./packem_shared/READ_ONLY_TOOL_DEFINITIONS-DGexf3Tn.mjs";import{O as F}from"./packem_shared/observability-tools-Ce0YK58T.mjs";import{serveStateless as G}from"./packem_shared/serveStateless-Db7J3pAO.mjs";export{r as AGENT_RUN_INPUT_SCHEMA,t as AGENT_STATUS_TOOL_NAME,N as LOCAL_SERVER_NAME,n as NO_DEPLOYMENT_MESSAGE,F as OBSERVABILITY_TOOL_DEFINITIONS,M as READ_ONLY_TOOL_DEFINITIONS,D as WRITE_TOOL_DEFINITIONS,T as agentToolDefinitions,c as callAgentTool,v as callTool,p as connectLocalStdio,m as connectStdio,I as createLocalMcpServer,s as createLunoraMcpServer,_ as createMcpFetchHandler,f as createPaidMcpServer,O as createToolServer,A as localTools,E as parseAgentsEnv,G as serveStateless,R as toolDefinitions};
@@ -0,0 +1 @@
1
+ const v="agents:agentRun",A="agents:agentThread",b="agents:agentMessages",g="lunora_agent_status",T=new Set(["cancelled","error","idle"]),x=6e4,U=600,L={properties:{prompt:{description:"The task or message for the agent.",type:"string"},threadKey:{description:"Reuse to continue a conversation; omit to start a new thread.",type:"string"},title:{description:"Optional thread title (first run only).",type:"string"}},required:["prompt"],type:"object"},P={properties:{threadKey:{description:"The thread key returned by an agent tool call.",type:"string"}},required:["threadKey"],type:"object"},p=t=>t.toolName??`agent_${t.name}`,G=t=>{if(t===void 0)return[];const n=[];for(const e of t.split(";")){const r=e.trim();if(r.length===0)continue;const o=r.indexOf(":");if(o<=0)continue;const s=r.slice(0,o).trim(),a=r.slice(o+1).trim();s.length===0||a.length===0||n.push({description:a,name:s})}return n},O=(t,n)=>n!==!0||t.length===0?[]:[...t.map(r=>({description:`${r.description} Starts a durable agent run and returns its final answer.`,inputSchema:L,name:p(r)})),{description:"Check the status of a durable agent run (and its answer if finished) by its threadKey.",inputSchema:P,name:g}],q=(t,n)=>t===g||n.some(e=>p(e)===t),k=()=>`mcp-${crypto.randomUUID()}`,l=t=>({__lunoraRef:t}),I=async t=>{await new Promise(n=>{setTimeout(n,t)})},d=t=>({content:[{text:JSON.stringify(t,void 0,2),type:"text"}]}),i=t=>({content:[{text:t,type:"text"}],isError:!0}),u=(t,n)=>{const e=t[n];return typeof e=="string"&&e.length>0?e:void 0},K=t=>{for(let n=t.length-1;n>=0;n-=1){const e=t[n],r=e?.toolCalls,o=Array.isArray(r)&&r.length>0;if(e?.role==="assistant"&&!o)return typeof e.content=="string"?e.content:""}return""},_=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",S=async(t,n,e,r)=>{const o=await t.query(l(b),{key:n});if(e==="error"){const s=r!==null&&typeof r=="object"?r.error:void 0;return d({error:typeof s=="string"?s:"the agent run failed",status:e,threadKey:n})}return d({status:e,text:K(o),threadKey:n})},R=async(t,n)=>{const e=u(n,"threadKey");if(e===void 0)return i('"threadKey" is required and must be a non-empty string');const r=await t.query(l(A),{key:e}),o=_(r);return T.has(o)?S(t,e,o,r):d({status:o==="unknown"?"running":o,threadKey:e})},C=async(t,n,e,r)=>{try{if(r.allowAgents!==!0)return i(`tool "${n}" is disabled: agent tools are off. Enable them with the LUNORA_MCP_ALLOW_AGENTS env var.`);if(n===g)return await R(t,e);const o=r.exposures.find(c=>p(c)===n);if(o===void 0)return i(`agent tool "${n}" is not exposed by this MCP server`);const s=u(e,"prompt");if(s===void 0)return i('"prompt" is required and must be a non-empty string');const a=u(e,"threadKey")??k(),f=u(e,"title"),{id:w}=await t.mutation(l(v),{agent:o.name,input:s,threadKey:a,...f===void 0?{}:{title:f}}),y=r.pollIntervalMs??U,E=r.maxWaitMs??x,N=r.wait??I,M=Math.max(1,Math.ceil(E/y));for(let c=0;c<M;c+=1){const h=await t.query(l(A),{key:a}),m=_(h);if(T.has(m))return await S(t,a,m,h);await N(y)}return d({hint:"call lunora_agent_status with this threadKey to poll for the answer",runId:w,status:"running",threadKey:a})}catch(o){const s=o instanceof Error?o.message:String(o);return i(s)}};export{L as AGENT_RUN_INPUT_SCHEMA,g as AGENT_STATUS_TOOL_NAME,O as agentToolDefinitions,C as callAgentTool,K as finalAnswer,q as isAgentToolName,G as parseAgentsEnv};
@@ -0,0 +1,4 @@
1
+ import{toDocsSearchHits as h}from"./toDocsSearchHits-CBLmtWXt.mjs";const f="https://lunora.sh",u=1e4,m=t=>t.endsWith("/")?t.slice(0,-1):t,p="\\",g=(t,n,i)=>{for(let s=i;s<t.length;s+=1)if(t[s]===n&&t[s-1]!==p)return s;return-1},d=t=>t.replaceAll(String.raw`\[`,"[").replaceAll(String.raw`\]`,"]").replaceAll(String.raw`\(`,"(").replaceAll(String.raw`\)`,")"),S=t=>{const n=t.trim();if(!n.startsWith("- ["))return;const i=n.lastIndexOf("](");if(i===-1)return;const s=g(n,")",i+2);if(s===-1)return;const o=d(n.slice(3,i).trim()),c=d(n.slice(i+2,s).trim());if(o.length===0||c.length===0)return;const e=n.slice(s+1).trim(),r=e.startsWith(":")?e.slice(1).trim():"";return r.length>0?{description:r,title:o,url:c}:{title:o,url:c}},x=t=>{if(!t.endsWith(")"))return t;const n=t.lastIndexOf(" (");if(n===-1)return t;const i=t.slice(n+2,-1);return i.startsWith("/")||i.startsWith("http")?t.slice(0,n).trim():t},y=(t,n)=>{for(const i of t.split(`
2
+ `)){if(i.startsWith("# "))return x(i.slice(2).trim());if(i.trim().length>0)break}return n},b=t=>{if(!t.startsWith("# "))return t;const n=t.indexOf(`
3
+ `);return n===-1?"":t.slice(n+1).trimStart()},A=(t={})=>{const n=m(t.baseUrl??f),i=t.fetch??globalThis.fetch,s=t.timeoutMs??u,o=async e=>{try{const r=await i(`${n}${e}`,{headers:{accept:"text/plain, application/json"},signal:AbortSignal.timeout(s)});return r.ok?{body:await r.text()}:{missing:!0}}catch(r){return{unreachable:r instanceof Error?r.message:String(r)}}},c=(e,r)=>{if("unreachable"in e)throw new Error(`could not reach the documentation site at ${n}${r}: ${e.unreachable}`);return"missing"in e?void 0:e.body};return{getPage:async e=>{const r=c(await o(`/llms.mdx${e}`),`/llms.mdx${e}`);if(!(r===void 0||r.trim().length===0))return{content:b(r),title:y(r,e),url:e}},listPages:async()=>{const e=c(await o("/llms.txt"),"/llms.txt");if(e===void 0)return[];const r=[];for(const l of e.split(`
4
+ `)){const a=S(l);a!==void 0&&r.push(a)}return r},search:async e=>{const r=`/api/search?query=${encodeURIComponent(e)}`,l=c(await o(r),r);if(l===void 0)return[];let a;try{a=JSON.parse(l)}catch{return[]}return Array.isArray(a)?h(a):[]}}};export{f as DEFAULT_DOCS_BASE_URL,u as DEFAULT_REQUEST_TIMEOUT_MS,A as createRemoteDocsIndex,S as parseIndexLine};
@@ -0,0 +1,3 @@
1
+ const T=10,I=50,h="docs",A=500,_={properties:{limit:{description:`Maximum hits to return (default ${String(10)}, max ${String(50)})`,type:"number"},query:{description:'Search terms, e.g. "shardBy" or "optimistic updates"',type:"string"}},required:["query"],type:"object"},p={properties:{url:{description:'Site-relative page URL from a search hit, e.g. "/docs/sharding"',type:"string"}},required:["url"],type:"object"},g={properties:{},type:"object"},i={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},u={annotations:{...i,title:"Search the Lunora documentation"},description:"Search the Lunora documentation and return matching pages and sections. Use this before writing Lunora code (schema, queries, mutations, actions, sharding, .global(), client hooks) so the answer reflects the framework's current API rather than a guess. Follow a hit with lunora_get_doc to read the full page.",inputSchema:_,name:"lunora_search_docs"},l={annotations:{...i,title:"Read a Lunora documentation page"},description:"Return one Lunora documentation page in full, as Markdown. Takes the `url` of a lunora_search_docs hit or a lunora_list_docs entry.",inputSchema:p,name:"lunora_get_doc"},d={annotations:{...i,title:"List the Lunora documentation pages"},description:"List every Lunora documentation page with its title and description. Prefer lunora_search_docs when you know what you're looking for.",inputSchema:g,name:"lunora_list_docs"},L=[u,l,d],o=e=>({content:[{text:JSON.stringify(e,void 0,2),type:"text"}]}),m=e=>({content:[{text:e,type:"text"}],isError:!0}),a=512,c=(e,t)=>{const n=e[t];if(typeof n!="string"||n.trim().length===0)throw new TypeError(`"${t}" is required and must be a non-empty string`);if(n.length>a)throw new RangeError(`"${t}" must be at most ${String(a)} characters`);return n.trim()},f=e=>{const t=typeof e=="string"?Number(e):e;return typeof t!="number"||!Number.isFinite(t)?10:Math.min(50,Math.max(1,Math.floor(t)))},S=e=>{let t=e.trim();if(t.startsWith("http://")||t.startsWith("https://")){const n=t.slice(t.indexOf("//")+2),r=n.indexOf("/");t=r===-1?"/":n.slice(r)}for(const n of["?","#"]){const r=t.indexOf(n);r!==-1&&(t=t.slice(0,r))}for(;t.endsWith("/")&&t.length>1;)t=t.slice(0,-1);if(t.startsWith("/")||(t=t.startsWith("docs/")?`/${t}`:`/${h}/${t}`),t.split("/").includes(".."))throw new RangeError(`"url" must not contain ".." segments: ${e}`);return t},y=e=>[{definition:u,handle:async t=>{const n=c(t,"query"),r=f(t.limit),s=(await e.search(n)).slice(0,r);return s.length===0?o({hits:[],note:`no documentation matched "${n}" — try fewer or more general terms, or lunora_list_docs to browse`}):o({hits:s})}},{definition:l,handle:async t=>{const n=S(c(t,"url")),r=await e.getPage(n);return r===void 0?m(`documentation page not found: ${n}. Use lunora_search_docs or lunora_list_docs to find a valid url.`):{content:[{text:`# ${r.title} (${r.url})
2
+
3
+ ${r.content}`,type:"text"}]}}},{definition:d,handle:async()=>{const t=await e.listPages();return t.length>500?o({note:`showing the first ${String(500)} of ${String(t.length)} pages — use lunora_search_docs to find the rest`,pages:t.slice(0,500)}):o(t)}}];export{T as DEFAULT_SEARCH_LIMIT,L as DOCS_TOOL_DEFINITIONS,a as MAX_ARGUMENT_LENGTH,A as MAX_LISTED_PAGES,I as MAX_SEARCH_LIMIT,y as docsTools,S as normalizeDocUrl};
@@ -0,0 +1 @@
1
+ import{createToolServer as d}from"./createToolServer-BtGuPyMU.mjs";import{serveStateless as a}from"./serveStateless-Db7J3pAO.mjs";import{docsResources as i}from"./DOCS_URI_SCHEME-CFANc3vr.mjs";import{docsTools as p}from"./DEFAULT_SEARCH_LIMIT-DWPt0hvR.mjs";const u="lunora-docs",y=128*1024,m=e=>({name:u,version:e??"0.0.0"}),l=e=>d(m(e.version),p(e.index),i(e.index)),S=e=>new TextEncoder().encode(e).length,t=(e,r,o)=>Response.json({error:{code:r,message:o},id:null,jsonrpc:"2.0"},{status:e}),f=async(e,r)=>{if(e.method!=="POST")return{parsedBody:void 0};const o={response:t(413,-32600,`request body exceeds ${String(r)} bytes`)},s=Number(e.headers.get("content-length"));if(Number.isFinite(s)&&s>r)return o;const c=await e.text();if(S(c)>r)return o;let n;try{n=JSON.parse(c)}catch{return{response:t(400,-32700,"parse error: body is not valid JSON")}}return Array.isArray(n)?{response:t(400,-32600,"batched requests are not supported: send one JSON-RPC message per request")}:{parsedBody:n}},g=e=>{const r=e.maxRequestBytes??y;return async o=>{const s=await f(o,r);return"response"in s?s.response:a(l(e),o,s.parsedBody===void 0?void 0:{parsedBody:s.parsedBody})}};export{y as DEFAULT_MAX_REQUEST_BYTES,u as DOCS_SERVER_NAME,g as createDocsMcpFetchHandler,l as createDocsMcpServer};
@@ -0,0 +1,3 @@
1
+ const r="lunora-docs:",i=t=>`${r}${t}`,n=t=>t.startsWith(r)?t.slice(r.length):void 0,c=t=>({list:async()=>(await t.listPages()).map(o=>({...o.description===void 0?{}:{description:o.description},mimeType:"text/markdown",name:o.title,uri:i(o.url)})),read:async s=>{const o=n(s);if(o===void 0)return;const e=await t.getPage(o);return e===void 0?void 0:{mimeType:"text/markdown",text:`# ${e.title} (${e.url})
2
+
3
+ ${e.content}`}}});export{r as DOCS_URI_SCHEME,c as docsResources,n as fromDocsUri,i as toDocsUri};
@@ -0,0 +1 @@
1
+ import{LunoraClient as f}from"@lunora/client";import{StdioServerTransport as p}from"@modelcontextprotocol/sdk/server/stdio.js";import{createToolServer as m}from"./createToolServer-BtGuPyMU.mjs";import{createRemoteDocsIndex as v}from"./DEFAULT_DOCS_BASE_URL-CZ3fVsSc.mjs";import{docsResources as h}from"./DOCS_URI_SCHEME-CFANc3vr.mjs";import{docsTools as y}from"./DEFAULT_SEARCH_LIMIT-DWPt0hvR.mjs";import{toolDefinitions as E,callTool as R}from"./READ_ONLY_TOOL_DEFINITIONS-DGexf3Tn.mjs";const O=(e,n)=>{if(e.size<n)return;const t=e.keys().next().value;t!==void 0&&e.delete(t)},l=e=>e.docs===!1?void 0:v({...e.docs?.baseUrl===void 0?{}:{baseUrl:e.docs.baseUrl},...e.fetch===void 0?{}:{fetch:e.fetch}}),_="lunora",S="no Lunora dev server is running for this project — start one with `lunora dev`, then call this tool again (call lunora_dev_status to check).",T=8,d=e=>{const n=new Map;return t=>{const r=JSON.stringify([t.url,t.token??""]),c=n.get(r);if(c!==void 0)return c;const o=new f({fetch:e,url:t.url});return t.token!==void 0&&t.token.length>0&&o.setAuthToken(t.token),O(n,T),n.set(r,o),o}},i=e=>e?.token!==void 0&&e.token.length>0,C=(e,n,t)=>{const r=typeof e=="function"?e:()=>e;return E(n,i(r())).map(c=>({definition:c,handle:async o=>{const s=r();return s===void 0?{content:[{text:S,type:"text"}],isError:!0}:R(t(s),c.name,o,n,i(s))}}))},P="lunora-spec:openrpc",g="lunora-spec:openapi",a=[{description:"The deployment's generated OpenRPC 1.x document — every RPC function's path, kind, and argument schema in one read, instead of list_functions plus one get_function_schema call per function.",fetch:async e=>e.fetchOpenRpc(),name:"OpenRPC specification",uri:P},{description:"The deployment's generated OpenAPI 3.1 document.",fetch:async e=>e.fetchOpenApi(),name:"OpenAPI specification",uri:g}],k=(e,n)=>{const t=typeof e=="function"?e:()=>e,r=async c=>{const o=t();if(o!==void 0)try{return await c.fetch(n(o))}catch{return}};return{list:async()=>(await Promise.all(a.map(async o=>await r(o)===void 0?void 0:{description:o.description,mimeType:"application/json",name:o.name,uri:o.uri}))).filter(o=>o!==void 0),read:async c=>{const o=a.find(u=>u.uri===c);if(o===void 0)return;const s=await r(o);return s===void 0?void 0:{mimeType:"application/json",text:JSON.stringify(s,void 0,2)}}}},w=e=>({list:async()=>(await Promise.all(e.map(async t=>t.list()))).flat(),read:async n=>{for(const t of e){const r=await t.read(n);if(r!==void 0)return r}}}),x=(e,n)=>{const t=[],r=l(e);return r!==void 0&&t.push(...y(r)),t.push(...e.extraTools??[]),e.deployment!==void 0&&t.push(...C(e.deployment,e.allowWrites??!1,n??d(e.fetch))),t},A=(e={})=>{const n=l(e),t=[];n!==void 0&&t.push(h(n));const r=d(e.fetch);return e.deployment!==void 0&&t.push(k(e.deployment,r)),m({name:_,version:e.version??"0.0.0"},x(e,r),t.length===0?void 0:w(t))},j=async(e={})=>{const n=A(e);return await n.connect(new p),n};export{_ as LOCAL_SERVER_NAME,S as NO_DEPLOYMENT_MESSAGE,g as OPENAPI_RESOURCE_URI,P as OPENRPC_RESOURCE_URI,j as connectLocalStdio,A as createLocalMcpServer,x as localTools};
@@ -0,0 +1 @@
1
+ import{D as T,M as a,O as L,a as s,c as _}from"./observability-tools-Ce0YK58T.mjs";export{T as DEFAULT_LIMIT,a as MAX_LIMIT,L as OBSERVABILITY_TOOL_DEFINITIONS,s as OBSERVABILITY_TOOL_NAMES,_ as callObservabilityTool};
@@ -0,0 +1 @@
1
+ import{LunoraError as u}from"@lunora/errors";import{O as A,e as d,a as w,c as E,o as c}from"./observability-tools-Ce0YK58T.mjs";const m={properties:{args:{description:"Arguments object passed to the function",type:"object"},functionPath:{description:'Function reference, e.g. "messages:send"',type:"string"},shardKey:{description:"Optional shard key when the function is .shardBy()-partitioned",type:"string"}},required:["functionPath"],type:"object"},g={properties:{},type:"object"},R={properties:{functionPath:{description:'Function reference, e.g. "messages:send"',type:"string"}},required:["functionPath"],type:"object"},l={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},I=[{annotations:{...l,title:"List deployment functions"},description:"List the deployment's public functions (queries, mutations, actions) with their kinds.",inputSchema:g,name:"lunora_list_functions"},{annotations:{...l,title:"List global tables"},description:"List the deployment's .global() tables and their column shapes.",inputSchema:g,name:"lunora_list_tables"},{annotations:{...l,title:"Describe a function's arguments"},description:"Return a function's argument JSON Schema and kind, so a caller can construct a valid arguments object. Call lunora_list_functions first to discover available function paths.",inputSchema:R,name:"lunora_get_function_schema"},{annotations:{...l,title:"Run a query"},description:"Run a query and return its result. Read-only.",inputSchema:m,name:"lunora_run_query"}],b=[{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:"Run a mutation (writes data)"},description:"Run a mutation and return its result. Writes data — use with care.",inputSchema:m,name:"lunora_run_mutation"},{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:"Run an action (may call external services)"},description:"Run an action and return its result. May call external services.",inputSchema:m,name:"lunora_run_action"}],L=new Set(b.map(t=>t.name)),U=(t,n=!1)=>[...I,...n===!0?A:[],...t===!0?b:[]],S=t=>{const{functionPath:n}=t;if(typeof n!="string"||n.length===0)throw new u("INTERNAL",'"functionPath" is required and must be a non-empty string');return n},O=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),N=t=>Array.isArray(t)?"an array":`a ${typeof t}`,v=t=>{if(t==null)return{};if(typeof t=="string"){let n;try{n=JSON.parse(t)}catch{throw new u("BAD_REQUEST",'"args" must be a JSON object; received a string that is not valid JSON')}if(!O(n))throw new u("BAD_REQUEST",`"args" must be a JSON object; the provided string decoded to ${N(n)}`);return n}if(!O(t))throw new u("BAD_REQUEST",`"args" must be a JSON object, got ${N(t)}`);return t},f=t=>{const n=S(t),e=v(t.args),o=typeof t.shardKey=="string"&&t.shardKey.length>0?t.shardKey:void 0;return{args:e,functionPath:n,shardKey:o}},p=t=>({__lunoraRef:t}),H=3e4,h=new WeakMap,y=t=>{const n=Date.now(),e=h.get(t);if(e!==void 0&&e.expiresAt>n)return e.promise;const o=t.listFunctions().catch(i=>{throw h.get(t)?.promise===o&&h.delete(t),i});return h.set(t,{expiresAt:n+H,promise:o}),o},_=async(t,n,e)=>{const i=(await y(t)).find(r=>r.path===n);if(i===void 0)throw new u("NOT_FOUND",`function not found or not public: ${n}`);if(i.kind!==e)throw new u("BAD_REQUEST",`function ${n} is a ${i.kind}, not a ${e}`)},k=async(t,n,e,o=!1,i=!1)=>{try{if(o!==!0&&L.has(n))return d(`tool "${n}" is disabled: this MCP server is read-only. Enable writes with the LUNORA_MCP_ALLOW_WRITES env var.`);if(w.has(n))return i!==!0?d(`tool "${n}" is unavailable: it reads the deployment's logs and errors, which needs an admin token. Set LUNORA_ADMIN_TOKEN (or pass --token) and reconnect.`):await E(t,n,e);switch(n){case"lunora_get_function_schema":{const r=S(e),s=(await y(t)).find(T=>T.path===r);return s===void 0?d(`function not found: ${r}`):c({args:s.args??[],kind:s.kind,path:s.path})}case"lunora_list_functions":return c(await y(t));case"lunora_list_tables":return c(await t.listGlobalTables());case"lunora_run_action":{const{args:r,functionPath:a,shardKey:s}=f(e);return await _(t,a,"action"),c(await t.action(p(a),r,{shardKey:s}))}case"lunora_run_mutation":{const{args:r,functionPath:a,shardKey:s}=f(e);return await _(t,a,"mutation"),c(await t.mutation(p(a),r,{shardKey:s}))}case"lunora_run_query":{const{args:r,functionPath:a,shardKey:s}=f(e);return await _(t,a,"query"),c(await t.query(p(a),r,{shardKey:s}))}default:return d(`unknown tool: ${n}`)}}catch(r){const a=r instanceof Error?r.message:String(r);return d(a)}};export{A as OBSERVABILITY_TOOL_DEFINITIONS,I as READ_ONLY_TOOL_DEFINITIONS,b as WRITE_TOOL_DEFINITIONS,k as callTool,U as toolDefinitions};
@@ -0,0 +1 @@
1
+ import{readFileSync as f}from"node:fs";import{dirname as c,join as v}from"node:path";import{fileURLToPath as g}from"node:url";import{LunoraClient as d}from"@lunora/client";import{LunoraError as h}from"@lunora/errors";import{Server as w}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as p}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as S,CallToolRequestSchema as T}from"@modelcontextprotocol/sdk/types.js";import{agentToolDefinitions as M,isAgentToolName as k,callAgentTool as y}from"./AGENT_RUN_INPUT_SCHEMA-DRSY74ed.mjs";import{toolDefinitions as A,callTool as R}from"./READ_ONLY_TOOL_DEFINITIONS-DGexf3Tn.mjs";const L=()=>{try{let e=c(g(import.meta.url));for(let r=0;r<8;r+=1){try{const o=f(v(e,"package.json"),"utf8"),t=JSON.parse(o);if(t.name==="@lunora/mcp"&&typeof t.version=="string"&&t.version.length>0)return t.version}catch{}const n=c(e);if(n===e)break;e=n}}catch{}return"0.0.0"},q={name:"lunora",version:L()},x=e=>{if(e.client!==void 0)return e.client;if(e.url===void 0)throw new h("INTERNAL","createLunoraMcpServer requires either a `client` or a `url`");const r=new d({fetch:e.fetch,url:e.url});return e.token!==void 0&&r.setAuthToken(e.token),r},I=e=>{const r=x(e),n=e.allowWrites??!1,o=e.allowAgents??!1,t=e.agents??[],s=typeof e.token=="string"&&e.token.length>0,a=new w(q,{capabilities:{tools:{}}});return a.setRequestHandler(S,()=>({tools:[...A(n,s),...M(t,o)]})),a.setRequestHandler(T,async m=>{const{arguments:u,name:l}=m.params,i=u??{};return k(l,t)?await y(r,l,i,{allowAgents:o,exposures:t,...e.agentMaxWaitMs===void 0?{}:{maxWaitMs:e.agentMaxWaitMs},...e.agentPollIntervalMs===void 0?{}:{pollIntervalMs:e.agentPollIntervalMs}}):await R(r,l,i,n,s)}),a},V=async e=>{const r=I(e);return await r.connect(new p),r};export{V as connectStdio,I as createLunoraMcpServer};
@@ -0,0 +1 @@
1
+ import{serveStateless as t}from"./serveStateless-Db7J3pAO.mjs";import{createLunoraMcpServer as o}from"./connectStdio-BCeI0Wqu.mjs";const p=e=>r=>t(o(e),r);export{p as createMcpFetchHandler,t as serveStateless};
@@ -0,0 +1 @@
1
+ import{LunoraError as u}from"@lunora/errors";import{Server as v}from"@modelcontextprotocol/sdk/server/index.js";import{ListToolsRequestSchema as y,CallToolRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{serveStateless as g}from"./serveStateless-Db7J3pAO.mjs";const S=async()=>{try{return(await import("@lunora/x402/charge")).createChargeMiddleware}catch(r){throw new u("INTERNAL",`paid MCP tools need the optional peer "@lunora/x402" — install it alongside @lunora/mcp to charge for tools (${r instanceof Error?r.message:String(r)})`)}},T={name:"lunora-paid-mcp",version:"0.0.0"},M="tools/call",d=r=>{if(typeof r!="object"||r===null)return;const{method:s,params:a}=r;if(s!==M||typeof a!="object"||a===null)return;const{name:i}=a;return typeof i=="string"?i:void 0},R=()=>Response.json({error:"A JSON-RPC batch may not reference a paid MCP tool; send paid tools/call requests individually."},{status:400}),b=()=>Response.json({error:"The request body could not be parsed as JSON; a priced MCP tool is registered, so the call cannot be gated."},{status:400}),B=r=>{const s=new Map,a=new Map,i=new Map,m=r.serverInfo??T,l=(e,t,o)=>{if(s.has(e.name))throw new u("BAD_REQUEST",`MCP tool "${e.name}" is already registered.`);const n={description:e.description,inputSchema:e.inputSchema,name:e.name};e.annotations!==void 0&&(n.annotations=e.annotations),s.set(e.name,{definition:n,handler:t}),o!==void 0&&a.set(e.name,o)},p=()=>{const e=new v(m,{capabilities:{tools:{}}});return e.setRequestHandler(y,()=>({tools:[...s.values()].map(t=>t.definition)})),e.setRequestHandler(w,async t=>{const o=s.get(t.params.name);return o===void 0?{content:[{text:`unknown tool: ${t.params.name}`,type:"text"}],isError:!0}:await o.handler(t.params.arguments??{})}),e},h=(e,t)=>{let o=i.get(e);if(o===void 0){const n=S().then(async c=>c({...r.charge,price:t},{resource:e})).catch(c=>{throw i.delete(e),c});o=n,i.set(e,n)}return o};return{fetchHandler:async e=>{let t;try{t=await e.clone().json()}catch{t=void 0}const o=()=>g(p(),e,t===void 0?void 0:{parsedBody:t});if(t===void 0&&a.size>0&&e.method==="POST")return b();if(Array.isArray(t))return t.some(f=>a.has(d(f)??""))?R():o();const n=d(t),c=n===void 0?void 0:a.get(n);return n===void 0||c===void 0?o():(await h(n,c)).handle(e,o)},paidTool:(e,t)=>{l(e,t,e.price)},tool:(e,t)=>{l(e,t)}}};export{B as createPaidMcpServer};
@@ -0,0 +1 @@
1
+ import{Server as l}from"@modelcontextprotocol/sdk/server/index.js";import{ListToolsRequestSchema as d,CallToolRequestSchema as f,ListResourcesRequestSchema as p,ReadResourceRequestSchema as R}from"@modelcontextprotocol/sdk/types.js";const v=(c,u,o)=>{const s=new Map;for(const e of u)s.has(e.definition.name)||s.set(e.definition.name,e);const m=[...s.values()].map(e=>e.definition),r=new l(c,{capabilities:o===void 0?{tools:{}}:{resources:{},tools:{}}});return r.setRequestHandler(d,()=>({tools:m})),r.setRequestHandler(f,async e=>{const{arguments:n,name:t}=e.params,i=s.get(t);if(i===void 0)return{content:[{text:`unknown tool: ${t}`,type:"text"}],isError:!0};try{return await i.handle(n??{})}catch(a){return{content:[{text:a instanceof Error?a.message:String(a),type:"text"}],isError:!0}}}),o!==void 0&&(r.setRequestHandler(p,async()=>({resources:[...await o.list()]})),r.setRequestHandler(R,async e=>{const{uri:n}=e.params,t=await o.read(n);if(t===void 0)throw new Error(`unknown resource: ${n}`);return{contents:[{mimeType:t.mimeType??"text/plain",text:t.text,uri:n}]}})),r};export{v as createToolServer};
@@ -0,0 +1 @@
1
+ import{LunoraError as v}from"@lunora/errors";import{ADMIN_FUNCTIONS as c}from"@lunora/shard-engine";const f=e=>{let t="";for(let s=0;s<e.length;s+=32768)t+=String.fromCharCode(...e.subarray(s,s+32768));return btoa(t)},b=(e,t)=>{if(typeof t=="bigint")return t.toString();if(t instanceof ArrayBuffer)return f(new Uint8Array(t));if(ArrayBuffer.isView(t)){const r=t;return f(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}return t},N=e=>JSON.parse(JSON.stringify(e,b)),R=e=>({content:[{text:e===void 0?"null":JSON.stringify(e,b,2),type:"text"}]}),u=e=>({...R(e),structuredContent:N(e)}),V=e=>({content:[{text:e,type:"text"}],isError:!0}),d={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},T=50,I=500,w=["1m","5m","15m","1h"],A=["open","resolved","ignored"],E=["trace","debug","log","info","warn","error","fatal"],h={description:"Shard to read from on a .shardBy()-partitioned deployment. Omit for the default (unsharded) shard — these reads are PER-SHARD, not deployment-wide.",type:"string"},y={description:`Maximum rows to return (default ${T.toString()}, clamped to ${I.toString()}).`,type:"number"},U=e=>{const t=typeof e=="number"?e:Number.NaN;return Number.isFinite(t)?Math.max(1,Math.min(Math.floor(t),I)):T},g=(e,t)=>t.includes(e)?e:void 0,_=e=>typeof e=="string"&&e.length>0?e:void 0,P={properties:{level:{description:`Keep only entries at this severity. One of: ${E.join(", ")}.`,type:"string"},limit:y,shardKey:h},type:"object"},L={properties:{functionPathPrefix:{description:'Keep only Issues whose function path starts with this, e.g. "messages:".',type:"string"},limit:y,shardKey:h,status:{description:`Triage status to keep. One of: ${A.join(", ")}. Default: all.`,type:"string"}},type:"object"},M={properties:{limit:y,shardKey:h},type:"object"},k={properties:{limit:y,range:{description:`Time window to report over. One of: ${w.join(", ")}. Default: 15m.`,type:"string"},shardKey:h},type:"object"},H={properties:{shardKey:h},type:"object"},x={properties:{entries:{description:"Recent log entries, NEWEST FIRST: { level, message, timestamp, functionPath?, fields? }.",type:"array"},total:{description:"Entries available before `limit`/`level` narrowed them.",type:"number"}},required:["entries","total"],type:"object"},C={properties:{issues:{description:"Grouped error Issues, newest first: { hash, title, count, status, functionPath, lastSeen, … }.",type:"array"}},required:["issues"],type:"object"},j={properties:{advisories:{description:"Schema/query advisories: { id, level, title, detail, … }.",type:"array"},total:{description:"Advisories available before `limit` narrowed them.",type:"number"}},required:["advisories","total"],type:"object"},q={properties:{buckets:{description:"Combined throughput/latency series across the range.",type:"array"},capped:{description:"True when the deployment's tracked-statement cap was reached, so coverage is partial.",type:"boolean"},entries:{description:"Per-statement activity in the range, hottest first.",type:"array"},total:{description:"Statements available before `limit` narrowed them.",type:"number"},trackedStatements:{description:"Distinct statements the deployment is tracking.",type:"number"}},required:["entries","buckets"],type:"object"},D={properties:{migrations:{description:"Every declared migration with its applied/pending state.",type:"array"}},required:["migrations"],type:"object"},G=[{annotations:{...d,title:"Read recent logs"},description:"Read the deployment's recent log entries (newest first) after running a function, to see what it printed and where it failed. In-memory and per-shard: resets when the shard hibernates.",inputSchema:P,name:"lunora_get_logs",outputSchema:x},{annotations:{...d,title:"List grouped error Issues"},description:"List errors grouped into Issues by fingerprint, with occurrence counts and triage status — the first call when asking what is currently broken, rather than reading raw logs.",inputSchema:L,name:"lunora_get_issues",outputSchema:C},{annotations:{...d,title:"List schema and query advisories"},description:"List the deployment's schema/query advisories (missing indexes, unsafe policies, and similar lints) before or after changing the schema.",inputSchema:M,name:"lunora_get_advisories",outputSchema:j},{annotations:{...d,title:"Read query insights"},description:"Read per-statement execution counts and latency over a recent time window, to find which query is slow or hot before optimizing one.",inputSchema:k,name:"lunora_get_query_insights",outputSchema:q},{annotations:{...d,title:"Read migration status"},description:"Read which migrations have been applied and which are pending, to check whether a schema change has actually landed on the deployment.",inputSchema:H,name:"lunora_get_migration_status",outputSchema:D}],Y=new Set(G.map(e=>e.name)),p=async(e,t,r,s)=>{const a={__lunoraRef:t};return e.query(a,r,{...s===void 0?{}:{shardKey:s}})},l=(e,t)=>{const r=e?.[t];return Array.isArray(r)?r:[]},$=async(e,t,r)=>{const s=_(r.shardKey),a=U(r.limit);switch(t){case"lunora_get_advisories":{const n=await p(e,c.getAdvisories,{},s),i=l(n,"advisories");return u({advisories:i.slice(0,a),total:i.length})}case"lunora_get_issues":{const n=g(r.status,A),i=_(r.functionPathPrefix),o=await p(e,c.getIssues,{limit:a,...n===void 0?{}:{status:n},...i===void 0?{}:{functionPathPrefix:i}},s);return u({issues:l(o,"issues")})}case"lunora_get_logs":{const n=g(r.level,E),i=await p(e,c.getLogs,{},s),o=l(i,"entries").filter(m=>n===void 0||m.level===n);return u({entries:o.slice(0,a),total:o.length})}case"lunora_get_migration_status":{const n=await p(e,c.migrationStatus,{},s);return u({migrations:l(n,"migrations")})}case"lunora_get_query_insights":{const n=g(r.range,w),i=await p(e,c.getQueryInsights,{...n===void 0?{}:{range:n}},s),o=l(i,"entries"),{buckets:m,capped:O,trackedStatements:S}=i??{};return u({buckets:Array.isArray(m)?m:[],capped:O===!0,entries:o.slice(0,a),total:o.length,trackedStatements:typeof S=="number"?S:o.length})}default:throw new v("INTERNAL",`unknown observability tool: ${t}`)}};export{T as D,I as M,G as O,Y as a,$ as c,V as e,R as o};