@zjazj/server 0.0.7 → 0.0.8

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/index.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { Hono, Context, ErrorHandler, NotFoundHandler, MiddlewareHandler } from 'hono';
1
+ import { Context, Hono, ErrorHandler, NotFoundHandler, MiddlewareHandler } from 'hono';
2
2
  import { V as Verifier, A as AuthUser } from './auth-Ckmm4C6y.js';
3
3
  export { a as AuthenticateOptions, O as ORGANIZATION_AUDIENCE_PREFIX, S as SupportSession, b as VerifierOptions, c as authenticate, d as bearerToken, e as createVerifier, g as getUser, r as requirePermission, f as requireRole, s as supportFromClaims, u as userFromClaims, v as verifierFromEnv } from './auth-Ckmm4C6y.js';
4
4
  import { D as Database } from './db-Dp7BB3Kc.js';
5
5
  export { A as APP_ID_PATTERN, a as APP_NAME_PATTERN, b as appBasePath, g as generateAppId, i as isUuid, c as isValidAppId, d as isValidAppName, u as uuidv7 } from './db-Dp7BB3Kc.js';
6
+ import { StandardSchemaWithJSON } from '@modelcontextprotocol/server';
6
7
  import 'jose';
7
8
  import 'drizzle-orm';
8
9
  import 'drizzle-orm/pg-core';
@@ -24,7 +25,83 @@ interface PermissionDefinition {
24
25
  /** Declare the app's permission catalog. Codes must be unique and use `app:resource:action`. */
25
26
  declare function definePermissions<const T extends readonly PermissionDefinition[]>(definitions: T): T;
26
27
 
27
- type Env$2 = Record<string, string | undefined>;
28
+ /** What a tool name may be: lower case, digits and underscores, at most 41 characters. */
29
+ declare const TOOL_NAME_PATTERN: RegExp;
30
+ /**
31
+ * What a tool does to data, for the people who choose whether an agent may call it on its
32
+ * own. A tool that only reads says so. Any other tool says whether it can destroy data.
33
+ */
34
+ type ToolAnnotations = {
35
+ readOnlyHint: true;
36
+ idempotentHint?: boolean;
37
+ /** True when the tool reaches a system outside the platform. */
38
+ openWorldHint?: boolean;
39
+ } | {
40
+ readOnlyHint: false;
41
+ /** True when the tool can delete or overwrite data, false when it only adds. */
42
+ destructiveHint: boolean;
43
+ /** True when calling it twice with the same input does no more than once. */
44
+ idempotentHint?: boolean;
45
+ /** True when the tool reaches a system outside the platform. */
46
+ openWorldHint?: boolean;
47
+ };
48
+ /**
49
+ * A schema for a tool's input or output: a Standard Schema that also gives its JSON Schema,
50
+ * such as a zod 4 object.
51
+ */
52
+ type ToolSchema = StandardSchemaWithJSON;
53
+ /** The value a schema produces from valid input. */
54
+ type ToolInput<S extends ToolSchema> = StandardSchemaWithJSON.InferOutput<S>;
55
+ interface ToolDefinition<S extends ToolSchema = ToolSchema> {
56
+ /** Unique in the app. The gateway shows it as `<app>_<name>`. */
57
+ name: string;
58
+ /** A name for people. */
59
+ title?: string;
60
+ /** What the tool does and when to use it, for the model. */
61
+ description: string;
62
+ /** The input, as an object schema. */
63
+ input: S;
64
+ /** The shape of what the handler returns, when it is an object. Optional. */
65
+ output?: ToolSchema;
66
+ /** The permission the caller needs. It must be in the app's permission catalog. */
67
+ permission: string;
68
+ annotations: ToolAnnotations;
69
+ /**
70
+ * Does the work, with the request's context: `getUser(c)` and `db(c)` work as in a route.
71
+ * Return a string, an object, an array, or nothing. Throw an `AppError` to refuse: its
72
+ * message reaches the caller. Any other error is reported as an internal error, and the
73
+ * request's database work is undone either way.
74
+ */
75
+ handler: (c: Context, input: ToolInput<S>) => unknown;
76
+ }
77
+ declare const TOOL_SET: unique symbol;
78
+ /** The tools of an app, as `defineTools` returns them. */
79
+ type ToolSet = readonly ToolDefinition[] & {
80
+ readonly [TOOL_SET]: true;
81
+ };
82
+ /** One tool as the manifest lists it, for `platform check` and the control plane's screens. */
83
+ interface ToolManifestEntry {
84
+ name: string;
85
+ title: string | null;
86
+ description: string;
87
+ permission: string;
88
+ annotations: ToolAnnotations;
89
+ }
90
+ /** True for what `defineTools` returned. */
91
+ declare function isToolSet(value: unknown): value is ToolSet;
92
+ /** The problems of a list of tools, one sentence each. Empty when there are none. */
93
+ declare function toolProblems(tools: readonly ToolDefinition[]): string[];
94
+ /**
95
+ * Declare an app's tools. Throws, with every problem found, when a name, a description, a
96
+ * permission or the annotations are not as the platform requires.
97
+ */
98
+ declare function defineTools<const S extends readonly ToolSchema[]>(tools: {
99
+ [K in keyof S]: ToolDefinition<S[K]>;
100
+ }): ToolSet;
101
+ /** The manifest's list of tools. */
102
+ declare function toolManifest(tools: readonly ToolDefinition[]): ToolManifestEntry[];
103
+
104
+ type Env$3 = Record<string, string | undefined>;
28
105
  /** The parts of the app's package.json the runtime uses. */
29
106
  interface AppManifest {
30
107
  /** URL segment and app code. */
@@ -56,14 +133,20 @@ interface PlatformManifest {
56
133
  title: string;
57
134
  description: string | null;
58
135
  }[];
136
+ /**
137
+ * The app's tools for agents, served at `<base>/mcp`: for `platform check` and the control
138
+ * plane's screens. The gateway reads the tools from the endpoint, not from here.
139
+ */
140
+ tools: ToolManifestEntry[];
59
141
  release_version: string | null;
60
142
  source_commit: string | null;
61
143
  }
62
144
  interface PlatformManifestOptions {
63
145
  manifest: AppManifest;
64
146
  permissions?: readonly PermissionDefinition[];
147
+ tools?: readonly ToolDefinition[];
65
148
  /** Read for `GIT_SHA`. Defaults to `process.env`. */
66
- env?: Env$2;
149
+ env?: Env$3;
67
150
  }
68
151
  /**
69
152
  * The app's manifest for the control plane. Every app answers it at
@@ -72,7 +155,7 @@ interface PlatformManifestOptions {
72
155
  */
73
156
  declare function platformManifest(options: PlatformManifestOptions): PlatformManifest;
74
157
 
75
- type Env$1 = Record<string, string | undefined>;
158
+ type Env$2 = Record<string, string | undefined>;
76
159
  interface CreateAppOptions {
77
160
  /** The app's package.json. `name` and `id` are required. */
78
161
  manifest: AppManifest;
@@ -87,9 +170,15 @@ interface CreateAppOptions {
87
170
  };
88
171
  /** Folder of the built frontend. Defaults to `dist/client` under the working directory. */
89
172
  staticDir?: string;
173
+ /**
174
+ * The app's tools for agents, from `defineTools`. They are served over MCP at
175
+ * `<basePath>/mcp` with the same checks as `api`, and listed in the manifest. Each tool's
176
+ * permission must be in `permissions`.
177
+ */
178
+ tools?: readonly ToolDefinition[];
90
179
  /** Token verifier. Defaults to one built from `LOGTO_*`. */
91
180
  verifier?: Verifier;
92
- env?: Env$1;
181
+ env?: Env$2;
93
182
  /** What the built-in routes call the control plane with. Defaults to `fetch`. For tests. */
94
183
  fetch?: typeof fetch;
95
184
  }
@@ -171,6 +260,102 @@ declare function toErrorResponse(error: unknown): {
171
260
  declare function errorHandler(onUnexpected?: (error: unknown, c: Context) => void): ErrorHandler;
172
261
  declare function notFoundHandler(): NotFoundHandler;
173
262
 
263
+ /** An authorization server's metadata (RFC 8414 or OpenID Connect Discovery), as served. */
264
+ interface OAuthServerMetadata {
265
+ issuer: string;
266
+ authorization_endpoint?: string;
267
+ token_endpoint?: string;
268
+ scopes_supported?: string[];
269
+ code_challenge_methods_supported?: string[];
270
+ token_endpoint_auth_methods_supported?: string[];
271
+ [key: string]: unknown;
272
+ }
273
+ /** What `discoverOAuth` found. Store it with the service. */
274
+ interface OAuthDiscovery {
275
+ /**
276
+ * The resource indicator to ask tokens for (RFC 8707), from the service's protected
277
+ * resource metadata (RFC 9728). Null when the service publishes none.
278
+ */
279
+ resource: string | null;
280
+ /** The authorization server's issuer. */
281
+ issuer: string;
282
+ /** The scopes the service says it supports, or the server's when it says none. */
283
+ scopes: string[];
284
+ server: OAuthServerMetadata;
285
+ }
286
+ /** Tokens as an app stores them, encrypted. */
287
+ interface OAuthTokens {
288
+ accessToken: string;
289
+ tokenType: string;
290
+ /** The refresh token to keep: a new one when the server rotated it. Null when none. */
291
+ refreshToken: string | null;
292
+ /** When the access token expires, in seconds since 1970. Null when the server says not. */
293
+ expiresAt: number | null;
294
+ scope: string | null;
295
+ }
296
+ /** Where to send the user, and what to keep until the user comes back. */
297
+ interface OAuthAuthorization {
298
+ url: string;
299
+ /** Keep with the attempt and compare in `exchangeCode`. */
300
+ state: string;
301
+ /** Keep secret, server side, until `exchangeCode`. */
302
+ codeVerifier: string;
303
+ }
304
+ interface OAuthRequestOptions {
305
+ /** What the requests are made with. Defaults to `fetch`. Pass a guarded fetch for an address a user typed. */
306
+ fetch?: typeof fetch;
307
+ /** Accept `http:` addresses. For a server on the developer machine only. */
308
+ allowHttp?: boolean;
309
+ }
310
+ interface OAuthClientOptions extends OAuthRequestOptions {
311
+ server: OAuthServerMetadata;
312
+ /** A client id typed in, or the address of a client metadata document. */
313
+ clientId: string;
314
+ /** Omit for a public client, which proves itself with PKCE alone. */
315
+ clientSecret?: string;
316
+ }
317
+ interface OAuthClient {
318
+ /** The address of the authorization request, with PKCE (S256) and a new state. */
319
+ authorize(input: {
320
+ redirectUri: string;
321
+ scope?: string;
322
+ resource?: string | null;
323
+ }): Promise<OAuthAuthorization>;
324
+ /**
325
+ * Exchange what the server sent to the redirect address: the whole address it called, or
326
+ * its query parameters (`code`, `state`, and `iss` when the server sends one).
327
+ */
328
+ exchangeCode(input: {
329
+ callback: string | Record<string, string>;
330
+ redirectUri: string;
331
+ state: string;
332
+ codeVerifier: string;
333
+ resource?: string | null;
334
+ }): Promise<OAuthTokens>;
335
+ /** Renew the tokens. `invalid_grant` means the user has to authorize again. */
336
+ refresh(refreshToken: string, input?: {
337
+ scope?: string;
338
+ resource?: string | null;
339
+ }): Promise<OAuthTokens>;
340
+ }
341
+ /** A refusal of the authorization server, or a server that could not be used. */
342
+ declare class OAuthError extends AppError {
343
+ /** The OAuth error code, such as `invalid_grant`, or `server_error` when there is none. */
344
+ readonly oauthError: string;
345
+ /** True when the grant is gone and only a new authorization helps. */
346
+ readonly needsAuthorization: boolean;
347
+ constructor(message: string, oauthError: string, cause?: unknown);
348
+ }
349
+ /**
350
+ * Find the authorization server of a service, such as an MCP server's address. Reads the
351
+ * service's protected resource metadata (RFC 9728) for the server, or takes the service's
352
+ * origin when it has none, then the server's metadata, as RFC 8414 and then as OpenID
353
+ * Connect Discovery.
354
+ */
355
+ declare function discoverOAuth(serviceUrl: string, options?: OAuthRequestOptions): Promise<OAuthDiscovery>;
356
+ /** A client of one authorization server, from the metadata `discoverOAuth` found. */
357
+ declare function createOAuthClient(options: OAuthClientOptions): OAuthClient;
358
+
174
359
  declare const DEFAULT_PAGE_SIZE = 20;
175
360
  declare const MAX_PAGE_SIZE = 100;
176
361
  interface PageParams {
@@ -193,7 +378,7 @@ interface Page<T> {
193
378
  declare function parsePage(source: Context | Record<string, string | undefined>): PageParams;
194
379
  declare function pageOf<T>(items: T[], total: number, params: PageParams): Page<T>;
195
380
 
196
- type Env = Record<string, string | undefined>;
381
+ type Env$1 = Record<string, string | undefined>;
197
382
  interface PlatformCall {
198
383
  /** Defaults to GET. */
199
384
  method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
@@ -203,7 +388,7 @@ interface PlatformCall {
203
388
  query?: Record<string, string | number | boolean | undefined>;
204
389
  }
205
390
  interface PlatformCallOptions {
206
- env?: Env;
391
+ env?: Env$1;
207
392
  fetch?: typeof fetch;
208
393
  /** Milliseconds to wait for the answer. Defaults to 10 seconds. */
209
394
  timeout?: number;
@@ -245,6 +430,39 @@ declare module 'hono' {
245
430
  }
246
431
  }
247
432
 
433
+ type Env = Record<string, string | undefined>;
434
+ /** A key shorter than this is refused. */
435
+ declare const MIN_SECRET_KEY_LENGTH = 32;
436
+ interface SecretBoxOptions {
437
+ /** The variable that holds the key, such as `ADMIN_SECRET_KEY`. Named in errors. */
438
+ keyVariable: string;
439
+ /**
440
+ * What the key is for, as the HKDF info, such as `admin/mcp-credentials/v1`. Two boxes
441
+ * with different purposes cannot read each other's values, also with one key.
442
+ */
443
+ purpose: string;
444
+ /** Read at every call. Defaults to `process.env`. */
445
+ env?: Env;
446
+ }
447
+ interface SecretBox {
448
+ /**
449
+ * Encrypt `plain`. `context` names what the value belongs to, such as `credential:<id>`.
450
+ * A value copied to another row no longer decrypts.
451
+ */
452
+ encrypt(plain: string, context: string): string;
453
+ /**
454
+ * Decrypt what `encrypt` returned for the same `context`. Throws 409
455
+ * `credential_unreadable` when the key changed or the value was damaged or moved.
456
+ */
457
+ decrypt(stored: string, context: string): string;
458
+ }
459
+ /**
460
+ * Encryption for the secrets an app stores. Without a key of at least 32 characters every
461
+ * call throws 503 `secret_key_missing`, except with the dev identity, which has a key of its
462
+ * own that protects nothing.
463
+ */
464
+ declare function createSecretBox(options: SecretBoxOptions): SecretBox;
465
+
248
466
  /** Thrown when a URL points somewhere the server must not call. */
249
467
  declare class UnsafeUrlError extends AppError {
250
468
  constructor(message: string);
@@ -266,4 +484,4 @@ interface UrlGuardOptions {
266
484
  */
267
485
  declare function assertPublicUrl(input: string | URL, options?: UrlGuardOptions): Promise<URL>;
268
486
 
269
- export { AppError, type AppErrorOptions, type AppManifest, AuthUser, ConflictError, type CreateAppOptions, DEFAULT_PAGE_SIZE, type ErrorBody, ForbiddenError, MAX_PAGE_SIZE, NotFoundError, type Page, type PageParams, type PermissionDefinition, type PlatformApp, type PlatformCall, type PlatformCallOptions, type PlatformManifest, type PlatformManifestOptions, REQUEST_ID_HEADER, type RequestContext, type RunningApp, UnauthorizedError, UnsafeUrlError, type UrlGuardOptions, ValidationError, Verifier, assertPublicUrl, callPlatform, coerceRequestId, createApp, definePermissions, errorHandler, getRequestContext, getRequestId, hasPermissions, isReservedAddress, notFoundHandler, pageOf, parsePage, permissionMatches, platformManifest, requestContext, toErrorResponse };
487
+ export { AppError, type AppErrorOptions, type AppManifest, AuthUser, ConflictError, type CreateAppOptions, DEFAULT_PAGE_SIZE, type ErrorBody, ForbiddenError, MAX_PAGE_SIZE, MIN_SECRET_KEY_LENGTH, NotFoundError, type OAuthAuthorization, type OAuthClient, type OAuthClientOptions, type OAuthDiscovery, OAuthError, type OAuthRequestOptions, type OAuthServerMetadata, type OAuthTokens, type Page, type PageParams, type PermissionDefinition, type PlatformApp, type PlatformCall, type PlatformCallOptions, type PlatformManifest, type PlatformManifestOptions, REQUEST_ID_HEADER, type RequestContext, type RunningApp, type SecretBox, type SecretBoxOptions, TOOL_NAME_PATTERN, type ToolAnnotations, type ToolDefinition, type ToolInput, type ToolManifestEntry, type ToolSchema, type ToolSet, UnauthorizedError, UnsafeUrlError, type UrlGuardOptions, ValidationError, Verifier, assertPublicUrl, callPlatform, coerceRequestId, createApp, createOAuthClient, createSecretBox, definePermissions, defineTools, discoverOAuth, errorHandler, getRequestContext, getRequestId, hasPermissions, isReservedAddress, isToolSet, notFoundHandler, pageOf, parsePage, permissionMatches, platformManifest, requestContext, toErrorResponse, toolManifest, toolProblems };
package/dist/index.js CHANGED
@@ -56,6 +56,71 @@ import { serve } from "@hono/node-server";
56
56
  import { serveStatic } from "@hono/node-server/serve-static";
57
57
  import { Hono } from "hono";
58
58
 
59
+ // src/tools.ts
60
+ var TOOL_NAME_PATTERN = /^[a-z][a-z0-9_]{0,40}$/;
61
+ var PERMISSION_CODE = /^[a-z][a-z0-9-]*(:[a-z][a-z0-9-]*)+$/;
62
+ var TOOL_SET = /* @__PURE__ */ Symbol.for("zjazj.platform.tools");
63
+ function isToolSet(value) {
64
+ return Array.isArray(value) && value[TOOL_SET] === true;
65
+ }
66
+ function toolProblems(tools) {
67
+ const problems = [];
68
+ const seen = /* @__PURE__ */ new Set();
69
+ tools.forEach((tool, index) => {
70
+ const name = typeof tool?.name === "string" ? tool.name : "";
71
+ const label = name ? `Tool ${name}` : `Tool ${index + 1}`;
72
+ if (!TOOL_NAME_PATTERN.test(name)) {
73
+ problems.push(
74
+ `${label}: the name must be lower-case letters, digits and underscores, start with a letter and have at most 41 characters. Got ${JSON.stringify(tool?.name)}.`
75
+ );
76
+ } else if (seen.has(name)) {
77
+ problems.push(`${label}: the name is used twice.`);
78
+ }
79
+ seen.add(name);
80
+ if (typeof tool?.description !== "string" || tool.description.trim() === "") {
81
+ problems.push(`${label}: the description is empty. Say what the tool does, for the model.`);
82
+ }
83
+ if (typeof tool?.permission !== "string" || !PERMISSION_CODE.test(tool.permission)) {
84
+ problems.push(
85
+ `${label}: the permission must be a code of the app's catalog, such as "app:item:read". Got ${JSON.stringify(tool?.permission)}.`
86
+ );
87
+ }
88
+ const annotations = tool?.annotations;
89
+ if (!annotations || typeof annotations.readOnlyHint !== "boolean") {
90
+ problems.push(`${label}: the annotations must say readOnlyHint, true or false.`);
91
+ } else if (annotations.readOnlyHint === false && typeof annotations.destructiveHint !== "boolean") {
92
+ problems.push(
93
+ `${label}: a tool that changes data must say destructiveHint, true when it can delete or overwrite data.`
94
+ );
95
+ }
96
+ const input = tool?.input;
97
+ if (!input || typeof input !== "object" || !("~standard" in input)) {
98
+ problems.push(`${label}: the input must be a schema, such as z.object({ ... }).`);
99
+ }
100
+ if (typeof tool?.handler !== "function") {
101
+ problems.push(`${label}: the handler is missing.`);
102
+ }
103
+ });
104
+ return problems;
105
+ }
106
+ function defineTools(tools) {
107
+ const list = [...tools];
108
+ const problems = toolProblems(list);
109
+ if (problems.length > 0) throw new Error(`Invalid tools:
110
+ - ${problems.join("\n- ")}`);
111
+ Object.defineProperty(list, TOOL_SET, { value: true });
112
+ return Object.freeze(list);
113
+ }
114
+ function toolManifest(tools) {
115
+ return tools.map((tool) => ({
116
+ name: tool.name,
117
+ title: tool.title ?? null,
118
+ description: tool.description,
119
+ permission: tool.permission,
120
+ annotations: tool.annotations
121
+ }));
122
+ }
123
+
59
124
  // src/manifest.ts
60
125
  function platformManifest(options) {
61
126
  const env = options.env ?? process.env;
@@ -73,6 +138,7 @@ function platformManifest(options) {
73
138
  title: permission.title,
74
139
  description: permission.description ?? null
75
140
  })),
141
+ tools: toolManifest(options.tools ?? []),
76
142
  release_version: manifest.version ?? null,
77
143
  source_commit: env.GIT_SHA || null
78
144
  };
@@ -194,6 +260,16 @@ function createApp(options) {
194
260
  env.BASE_URL || (env.NODE_ENV === "production" ? appBasePath(manifest.name) : "/")
195
261
  );
196
262
  configureLog({ app: manifest.name, env: env.ENV || env.NODE_ENV || "development" });
263
+ const tools = options.tools ?? [];
264
+ if (options.permissions) {
265
+ const catalog = new Set(options.permissions.map((permission) => permission.code));
266
+ const unknown = tools.filter((tool) => !catalog.has(tool.permission));
267
+ if (unknown.length > 0) {
268
+ throw new Error(
269
+ `Tools need permissions that are not in the catalog: ${unknown.map((tool) => `${tool.name} (${tool.permission})`).join(", ")}`
270
+ );
271
+ }
272
+ }
197
273
  const databaseOptions = typeof options.database === "object" ? options.database : options.database ? {} : void 0;
198
274
  const getDatabase = () => {
199
275
  if (!databaseOptions) {
@@ -271,7 +347,7 @@ function createApp(options) {
271
347
  root.use("/internal/*", internalCallersOnly);
272
348
  root.get(
273
349
  "/internal/_platform/manifest",
274
- (c) => c.json(platformManifest({ manifest, permissions: options.permissions, env }))
350
+ (c) => c.json(platformManifest({ manifest, permissions: options.permissions, tools, env }))
275
351
  );
276
352
  root.all("/internal/_platform/*", (c) => c.notFound());
277
353
  root.route("/internal/delegated", delegated);
@@ -292,6 +368,23 @@ function createApp(options) {
292
368
  scoped.route("/api/_platform", platformRoutes);
293
369
  scoped.route("/api", api);
294
370
  scoped.all("/api/*", (c) => c.notFound());
371
+ if (tools.length > 0) {
372
+ const mcp = new Hono();
373
+ mcp.use("*", authenticate({ verifier: options.verifier, env }));
374
+ let route;
375
+ mcp.all("/", async (c) => {
376
+ if (!route) {
377
+ const { createMcpRoute } = await import("./mcp-UM4G354G.js");
378
+ route ??= createMcpRoute({
379
+ manifest,
380
+ tools,
381
+ ...databaseOptions ? { database: getDatabase } : {}
382
+ });
383
+ }
384
+ return route(c);
385
+ });
386
+ scoped.route("/mcp", mcp);
387
+ }
295
388
  const staticDir = path.resolve(options.staticDir ?? "dist/client");
296
389
  const indexFile = path.join(staticDir, "index.html");
297
390
  if (existsSync(indexFile)) {
@@ -354,6 +447,197 @@ function createApp(options) {
354
447
  };
355
448
  }
356
449
 
450
+ // src/oauth.ts
451
+ import * as client from "openid-client";
452
+ var OAuthError = class extends AppError {
453
+ /** The OAuth error code, such as `invalid_grant`, or `server_error` when there is none. */
454
+ oauthError;
455
+ /** True when the grant is gone and only a new authorization helps. */
456
+ needsAuthorization;
457
+ constructor(message, oauthError, cause) {
458
+ const needsAuthorization = oauthError === "invalid_grant" || oauthError === "access_denied";
459
+ super(message, {
460
+ code: needsAuthorization ? "oauth_needs_authorization" : "oauth_failed",
461
+ status: needsAuthorization ? 409 : 502,
462
+ cause
463
+ });
464
+ this.oauthError = oauthError;
465
+ this.needsAuthorization = needsAuthorization;
466
+ }
467
+ };
468
+ function toOAuthError(error, doing) {
469
+ if (error instanceof OAuthError) return error;
470
+ if (error instanceof client.ResponseBodyError || error instanceof client.AuthorizationResponseError) {
471
+ const description = error.error_description ? `: ${error.error_description}` : "";
472
+ return new OAuthError(`${doing} was refused (${error.error}${description})`, error.error, error);
473
+ }
474
+ return new OAuthError(`${doing} failed`, "server_error", error);
475
+ }
476
+ function customFetch2(options) {
477
+ const fetcher = options.fetch;
478
+ return fetcher ? (url, init) => fetcher(url, init) : void 0;
479
+ }
480
+ async function getJson(url, options) {
481
+ const response = await (options.fetch ?? fetch)(url, {
482
+ headers: { Accept: "application/json" },
483
+ redirect: "error"
484
+ });
485
+ if (!response.ok) return void 0;
486
+ const body = await response.json().catch(() => void 0);
487
+ return body && typeof body === "object" ? body : void 0;
488
+ }
489
+ async function protectedResource(service, options) {
490
+ const path2 = service.pathname.replace(/\/+$/, "");
491
+ const candidates = [
492
+ ...path2 ? [new URL(`/.well-known/oauth-protected-resource${path2}`, service)] : [],
493
+ new URL("/.well-known/oauth-protected-resource", service)
494
+ ];
495
+ for (const candidate of candidates) {
496
+ const metadata = await getJson(candidate, options).catch(() => void 0);
497
+ if (!metadata) continue;
498
+ const servers = Array.isArray(metadata.authorization_servers) ? metadata.authorization_servers.filter((value) => typeof value === "string") : [];
499
+ const resource = typeof metadata.resource === "string" ? metadata.resource : service.href;
500
+ const scopes = Array.isArray(metadata.scopes_supported) ? metadata.scopes_supported.filter((value) => typeof value === "string") : [];
501
+ return { resource, servers, scopes };
502
+ }
503
+ return void 0;
504
+ }
505
+ function discoveryOptions(options, algorithm) {
506
+ const fetcher = customFetch2(options);
507
+ return {
508
+ algorithm,
509
+ ...options.allowHttp ? { execute: [client.allowInsecureRequests] } : {},
510
+ ...fetcher ? { [client.customFetch]: fetcher } : {}
511
+ };
512
+ }
513
+ async function discoverOAuth(serviceUrl, options = {}) {
514
+ const service = new URL(serviceUrl);
515
+ if (service.protocol !== "https:" && !(options.allowHttp && service.protocol === "http:")) {
516
+ throw new OAuthError("The service address must use https", "invalid_request");
517
+ }
518
+ const found = await protectedResource(service, options);
519
+ const issuer = found?.servers[0] ?? service.origin;
520
+ let lastError;
521
+ for (const algorithm of ["oauth2", "oidc"]) {
522
+ try {
523
+ const config = await client.discovery(
524
+ new URL(issuer),
525
+ "discovery",
526
+ void 0,
527
+ void 0,
528
+ discoveryOptions(options, algorithm)
529
+ );
530
+ const server = { ...config.serverMetadata() };
531
+ if (!server.authorization_endpoint || !server.token_endpoint) {
532
+ throw new OAuthError(
533
+ "The authorization server names no authorization or token endpoint",
534
+ "invalid_server"
535
+ );
536
+ }
537
+ return {
538
+ resource: found?.resource ?? null,
539
+ issuer: server.issuer,
540
+ scopes: found?.scopes.length ? found.scopes : server.scopes_supported ?? [],
541
+ server
542
+ };
543
+ } catch (error) {
544
+ lastError = error;
545
+ }
546
+ }
547
+ throw toOAuthError(lastError, `Finding the authorization server of ${service.origin}`);
548
+ }
549
+ function tokensFrom(response, previousRefreshToken) {
550
+ const expiresIn = response.expiresIn();
551
+ return {
552
+ accessToken: response.access_token,
553
+ tokenType: response.token_type ?? "bearer",
554
+ refreshToken: response.refresh_token ?? previousRefreshToken,
555
+ expiresAt: expiresIn === void 0 ? null : Math.floor(Date.now() / 1e3) + expiresIn,
556
+ scope: response.scope ?? null
557
+ };
558
+ }
559
+ function createOAuthClient(options) {
560
+ const { server, clientId, clientSecret } = options;
561
+ const methods = server.token_endpoint_auth_methods_supported;
562
+ const authentication = !clientSecret ? client.None() : !methods || methods.includes("client_secret_basic") ? client.ClientSecretBasic(clientSecret) : client.ClientSecretPost(clientSecret);
563
+ const config = new client.Configuration(
564
+ server,
565
+ clientId,
566
+ void 0,
567
+ authentication
568
+ );
569
+ const fetcher = customFetch2(options);
570
+ if (fetcher) config[client.customFetch] = fetcher;
571
+ if (options.allowHttp) client.allowInsecureRequests(config);
572
+ const parameters = (values) => Object.fromEntries(
573
+ Object.entries(values).filter((entry) => Boolean(entry[1]))
574
+ );
575
+ return {
576
+ async authorize(input) {
577
+ const supported = server.code_challenge_methods_supported;
578
+ if (supported && !supported.includes("S256")) {
579
+ throw new OAuthError(
580
+ "The authorization server does not support PKCE with S256",
581
+ "invalid_server"
582
+ );
583
+ }
584
+ const codeVerifier = client.randomPKCECodeVerifier();
585
+ const state = client.randomState();
586
+ const url = client.buildAuthorizationUrl(
587
+ config,
588
+ parameters({
589
+ redirect_uri: input.redirectUri,
590
+ response_type: "code",
591
+ code_challenge: await client.calculatePKCECodeChallenge(codeVerifier),
592
+ code_challenge_method: "S256",
593
+ state,
594
+ scope: input.scope,
595
+ resource: input.resource
596
+ })
597
+ );
598
+ return { url: url.href, state, codeVerifier };
599
+ },
600
+ async exchangeCode(input) {
601
+ let callback;
602
+ if (typeof input.callback === "string") {
603
+ callback = new URL(input.callback);
604
+ } else {
605
+ callback = new URL(input.redirectUri);
606
+ for (const [name, value] of Object.entries(input.callback)) {
607
+ callback.searchParams.set(name, value);
608
+ }
609
+ }
610
+ try {
611
+ const response = await client.authorizationCodeGrant(
612
+ config,
613
+ callback,
614
+ {
615
+ pkceCodeVerifier: input.codeVerifier,
616
+ expectedState: input.state,
617
+ idTokenExpected: false
618
+ },
619
+ parameters({ redirect_uri: input.redirectUri, resource: input.resource })
620
+ );
621
+ return tokensFrom(response, null);
622
+ } catch (error) {
623
+ throw toOAuthError(error, "The authorization");
624
+ }
625
+ },
626
+ async refresh(refreshToken, input = {}) {
627
+ try {
628
+ const response = await client.refreshTokenGrant(
629
+ config,
630
+ refreshToken,
631
+ parameters({ scope: input.scope, resource: input.resource })
632
+ );
633
+ return tokensFrom(response, refreshToken);
634
+ } catch (error) {
635
+ throw toOAuthError(error, "Renewing the token");
636
+ }
637
+ }
638
+ };
639
+ }
640
+
357
641
  // src/pagination.ts
358
642
  var DEFAULT_PAGE_SIZE = 20;
359
643
  var MAX_PAGE_SIZE = 100;
@@ -378,6 +662,63 @@ function pageOf(items, total, params) {
378
662
  return { items, page: params.page, page_size: params.pageSize, total };
379
663
  }
380
664
 
665
+ // src/secrets.ts
666
+ import { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from "crypto";
667
+ var VERSION = "v1";
668
+ var TAG_LENGTH = 16;
669
+ var MIN_SECRET_KEY_LENGTH = 32;
670
+ var DEV_SECRET = "platform-local-development-key-not-a-secret";
671
+ function createSecretBox(options) {
672
+ const { keyVariable, purpose } = options;
673
+ if (!keyVariable || !purpose) throw new Error("createSecretBox needs keyVariable and purpose");
674
+ let derived;
675
+ const key = () => {
676
+ const env = options.env ?? process.env;
677
+ const secret = env[keyVariable] || (isDevIdentityEnabled(env) ? DEV_SECRET : "");
678
+ if (secret.length < MIN_SECRET_KEY_LENGTH) {
679
+ throw new AppError(
680
+ `Secrets cannot be stored or read: the app has no encryption key. Ask the platform operator to set ${keyVariable}.`,
681
+ { code: "secret_key_missing", status: 503 }
682
+ );
683
+ }
684
+ if (derived?.from !== secret) {
685
+ const bytes = hkdfSync("sha256", secret, Buffer.alloc(0), purpose, 32);
686
+ derived = { from: secret, key: Buffer.from(bytes) };
687
+ }
688
+ return derived.key;
689
+ };
690
+ return {
691
+ encrypt(plain, context) {
692
+ const iv = randomBytes(12);
693
+ const cipher = createCipheriv("aes-256-gcm", key(), iv, { authTagLength: TAG_LENGTH });
694
+ cipher.setAAD(Buffer.from(context, "utf8"));
695
+ const data = Buffer.concat([cipher.update(plain, "utf8"), cipher.final()]);
696
+ return [VERSION, iv, cipher.getAuthTag(), data].map((part) => typeof part === "string" ? part : part.toString("base64url")).join(".");
697
+ },
698
+ decrypt(stored, context) {
699
+ const secretKey = key();
700
+ const [version, iv, tag, data] = stored.split(".");
701
+ try {
702
+ if (version !== VERSION || !iv || !tag || data === void 0) throw new Error("format");
703
+ const decipher = createDecipheriv("aes-256-gcm", secretKey, Buffer.from(iv, "base64url"), {
704
+ authTagLength: TAG_LENGTH
705
+ });
706
+ decipher.setAAD(Buffer.from(context, "utf8"));
707
+ decipher.setAuthTag(Buffer.from(tag, "base64url"));
708
+ return Buffer.concat([
709
+ decipher.update(Buffer.from(data, "base64url")),
710
+ decipher.final()
711
+ ]).toString("utf8");
712
+ } catch {
713
+ throw new AppError("The stored secret cannot be read. Enter it again.", {
714
+ code: "credential_unreadable",
715
+ status: 409
716
+ });
717
+ }
718
+ }
719
+ };
720
+ }
721
+
381
722
  // src/url-guard.ts
382
723
  import { lookup as dnsLookup } from "dns/promises";
383
724
  import { BlockList, isIP } from "net";
@@ -474,9 +815,12 @@ export {
474
815
  DEFAULT_PAGE_SIZE,
475
816
  ForbiddenError,
476
817
  MAX_PAGE_SIZE,
818
+ MIN_SECRET_KEY_LENGTH,
477
819
  NotFoundError,
820
+ OAuthError,
478
821
  ORGANIZATION_AUDIENCE_PREFIX,
479
822
  REQUEST_ID_HEADER,
823
+ TOOL_NAME_PATTERN,
480
824
  UnauthorizedError,
481
825
  UnsafeUrlError,
482
826
  ValidationError,
@@ -487,8 +831,12 @@ export {
487
831
  callPlatform,
488
832
  coerceRequestId,
489
833
  createApp,
834
+ createOAuthClient,
835
+ createSecretBox,
490
836
  createVerifier,
491
837
  definePermissions,
838
+ defineTools,
839
+ discoverOAuth,
492
840
  errorHandler,
493
841
  generateAppId,
494
842
  getRequestContext,
@@ -496,6 +844,7 @@ export {
496
844
  getUser,
497
845
  hasPermissions,
498
846
  isReservedAddress,
847
+ isToolSet,
499
848
  isUuid,
500
849
  isValidAppId,
501
850
  isValidAppName,
@@ -509,6 +858,8 @@ export {
509
858
  requireRole,
510
859
  supportFromClaims,
511
860
  toErrorResponse,
861
+ toolManifest,
862
+ toolProblems,
512
863
  userFromClaims,
513
864
  uuidv7,
514
865
  verifierFromEnv
@@ -0,0 +1,139 @@
1
+ import {
2
+ log
3
+ } from "./chunk-26AAYRI3.js";
4
+ import {
5
+ bearerToken,
6
+ getUser,
7
+ hasPermissions
8
+ } from "./chunk-EIZ24ILA.js";
9
+ import {
10
+ AppError
11
+ } from "./chunk-UWDDQH25.js";
12
+ import "./chunk-NMKEVYGN.js";
13
+ import {
14
+ getRequestId
15
+ } from "./chunk-ERGI2X5S.js";
16
+
17
+ // src/mcp.ts
18
+ import {
19
+ createMcpHandler,
20
+ McpServer,
21
+ originValidationResponse
22
+ } from "@modelcontextprotocol/server";
23
+ var CONTEXT = "platformContext";
24
+ function contextOf(request) {
25
+ const c = request.authInfo?.extra?.[CONTEXT];
26
+ if (!c) throw new Error("The MCP endpoint was called without its request context");
27
+ return c;
28
+ }
29
+ function toResult(value) {
30
+ if (typeof value === "string") return { content: [{ type: "text", text: value }] };
31
+ if (value === void 0 || value === null) return { content: [{ type: "text", text: "Done." }] };
32
+ const text = JSON.stringify(value);
33
+ if (typeof value === "object" && !Array.isArray(value)) {
34
+ return {
35
+ content: [{ type: "text", text }],
36
+ structuredContent: value
37
+ };
38
+ }
39
+ return { content: [{ type: "text", text }] };
40
+ }
41
+ function failure(tool, error) {
42
+ if (error instanceof AppError) {
43
+ log.info("Tool call refused", { tool, code: error.code, status: error.status });
44
+ return { content: [{ type: "text", text: `${error.code}: ${error.message}` }], isError: true };
45
+ }
46
+ log.error("Tool call failed", { tool, err: error });
47
+ return {
48
+ content: [
49
+ {
50
+ type: "text",
51
+ text: `internal_error: The tool failed. Trace ${getRequestId() ?? ""}`.trim()
52
+ }
53
+ ],
54
+ isError: true
55
+ };
56
+ }
57
+ function createMcpRoute(options) {
58
+ const { manifest, tools } = options;
59
+ const inTenant = async (c, work) => {
60
+ if (!options.database) return work();
61
+ const { withTenant } = await import("./db.js");
62
+ return withTenant(await options.database(), getUser(c).tenantId, async (tx) => {
63
+ c.set("db", tx);
64
+ return work();
65
+ });
66
+ };
67
+ const serverFor = (request) => {
68
+ const c = contextOf(request);
69
+ const user = getUser(c);
70
+ const server = new McpServer(
71
+ {
72
+ name: manifest.name,
73
+ title: manifest.platform?.title ?? manifest.name,
74
+ version: manifest.version ?? "0.0.0"
75
+ },
76
+ // What a caller is shown depends on the caller's permissions.
77
+ { cacheHints: { "tools/list": { ttlMs: 0, cacheScope: "private" } } }
78
+ );
79
+ for (const tool of tools) {
80
+ const registered = server.registerTool(
81
+ tool.name,
82
+ {
83
+ ...tool.title ? { title: tool.title } : {},
84
+ description: tool.description,
85
+ inputSchema: tool.input,
86
+ ...tool.output ? { outputSchema: tool.output } : {},
87
+ annotations: { ...tool.title ? { title: tool.title } : {}, ...tool.annotations }
88
+ },
89
+ async (input) => {
90
+ try {
91
+ if (!hasPermissions(getUser(c).permissions, [tool.permission])) {
92
+ throw new AppError(`requires permission: ${tool.permission}`, {
93
+ code: "insufficient_permission",
94
+ status: 403
95
+ });
96
+ }
97
+ const result = toResult(await inTenant(c, () => tool.handler(c, input)));
98
+ log.info("Tool call", { tool: tool.name });
99
+ return result;
100
+ } catch (error) {
101
+ return failure(tool.name, error);
102
+ }
103
+ }
104
+ );
105
+ if (!hasPermissions(user.permissions, [tool.permission])) registered.remove();
106
+ }
107
+ return server;
108
+ };
109
+ let handler;
110
+ return async (c) => {
111
+ const refused = originValidationResponse(c.req.raw, [new URL(c.req.url).hostname]);
112
+ if (refused) return refused;
113
+ if (!handler) {
114
+ const warn = console.warn;
115
+ console.warn = () => {
116
+ };
117
+ try {
118
+ handler = createMcpHandler(serverFor, {
119
+ responseMode: "json",
120
+ onerror: (error) => log.warn("MCP request refused", { err: error })
121
+ });
122
+ } finally {
123
+ console.warn = warn;
124
+ }
125
+ }
126
+ const user = getUser(c);
127
+ return handler.fetch(c.req.raw, {
128
+ authInfo: {
129
+ token: bearerToken(c.req.header("Authorization")) ?? "",
130
+ clientId: user.id,
131
+ scopes: user.permissions,
132
+ extra: { [CONTEXT]: c }
133
+ }
134
+ });
135
+ };
136
+ }
137
+ export {
138
+ createMcpRoute
139
+ };
package/dist/testing.d.ts CHANGED
@@ -22,5 +22,16 @@ declare const TEST_TENANT_ID = "0190a000-0000-7000-8000-0000000000a1";
22
22
  * network call.
23
23
  */
24
24
  declare function createTestIssuer(issuer?: string): Promise<TestIssuer>;
25
+ /** The MCP revision `mcpRequest` speaks. */
26
+ declare const MCP_PROTOCOL_VERSION = "2026-07-28";
27
+ /**
28
+ * One request to an app's MCP endpoint, as a client of MCP 2026-07-28 sends it: the
29
+ * method and its name in headers, the revision and the client's capabilities in `_meta`.
30
+ * Pass the token in `headers`. Read the answer with `await response.json()`: `result` or
31
+ * `error`.
32
+ */
33
+ declare function mcpRequest(url: string, method: string, params?: Record<string, unknown>, init?: {
34
+ headers?: Record<string, string>;
35
+ }): Request;
25
36
 
26
- export { type SignOptions, TEST_TENANT_ID, type TestIssuer, createTestIssuer };
37
+ export { MCP_PROTOCOL_VERSION, type SignOptions, TEST_TENANT_ID, type TestIssuer, createTestIssuer, mcpRequest };
package/dist/testing.js CHANGED
@@ -35,7 +35,37 @@ async function createTestIssuer(issuer = "https://auth.test/oidc") {
35
35
  }
36
36
  };
37
37
  }
38
+ var MCP_PROTOCOL_VERSION = "2026-07-28";
39
+ function mcpRequest(url, method, params = {}, init = {}) {
40
+ const named = params.name ?? params.uri;
41
+ return new Request(url, {
42
+ method: "POST",
43
+ headers: {
44
+ "Content-Type": "application/json",
45
+ Accept: "application/json, text/event-stream",
46
+ "MCP-Protocol-Version": MCP_PROTOCOL_VERSION,
47
+ "Mcp-Method": method,
48
+ ...typeof named === "string" ? { "Mcp-Name": named } : {},
49
+ ...init.headers
50
+ },
51
+ body: JSON.stringify({
52
+ jsonrpc: "2.0",
53
+ id: 1,
54
+ method,
55
+ params: {
56
+ ...params,
57
+ _meta: {
58
+ "io.modelcontextprotocol/protocolVersion": MCP_PROTOCOL_VERSION,
59
+ "io.modelcontextprotocol/clientCapabilities": {},
60
+ "io.modelcontextprotocol/clientInfo": { name: "test", version: "1.0.0" }
61
+ }
62
+ }
63
+ })
64
+ });
65
+ }
38
66
  export {
67
+ MCP_PROTOCOL_VERSION,
39
68
  TEST_TENANT_ID,
40
- createTestIssuer
69
+ createTestIssuer,
70
+ mcpRequest
41
71
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zjazj/server",
3
- "version": "0.0.7",
3
+ "version": "0.0.8",
4
4
  "description": "Backend runtime for platform apps: auth, logging, tenant-safe database access and app assembly on Hono.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -40,8 +40,10 @@
40
40
  },
41
41
  "dependencies": {
42
42
  "@hono/node-server": "^1.19.18",
43
+ "@modelcontextprotocol/server": "^2.4.0",
43
44
  "hono": "^4.13.17",
44
45
  "jose": "^6.2.17",
46
+ "openid-client": "^6.9.1",
45
47
  "pino": "^10.4.0"
46
48
  },
47
49
  "peerDependencies": {
@@ -63,7 +65,8 @@
63
65
  "devDependencies": {
64
66
  "@electric-sql/pglite": "^0.5.16",
65
67
  "drizzle-orm": "^0.45.4",
66
- "postgres": "^3.4.9"
68
+ "postgres": "^3.4.9",
69
+ "zod": "^4.6.7"
67
70
  },
68
71
  "publishConfig": {
69
72
  "access": "public",