@cubicecho/server-kit 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -37,8 +37,8 @@ It waits for Postgres, creates the database when it is missing, and refuses a se
37
37
 
38
38
  How a server is built on the kit, written for an agent, is the Markdown in
39
39
  [`skill/`](https://github.com/cubicecho/server-kit/tree/main/skill): `SKILL.md`, which routes, and one
40
- file per job (boot, tables and ids, auth, SSO, errors and limits, the MCP door, defaults, tests,
41
- adopting the kit). It ships in the package, so `node_modules/@cubicecho/server-kit/skill/` always
40
+ file per job (boot, tables and ids, auth, SSO, errors and limits, the MCP door, discovery, defaults,
41
+ tests, adopting the kit). It ships in the package, so `node_modules/@cubicecho/server-kit/skill/` always
42
42
  matches the installed version. Put the directory wherever your agent reads skills and keep it whole,
43
43
  because the files link each other by relative path. No file is over 25 KB, so a skills server can hand
44
44
  each one over whole.
@@ -82,7 +82,7 @@ await gate.as(code, () => auth.api.pairOidcProvider({ body: { setupUrl }, header
82
82
  ```
83
83
 
84
84
  - With `setup`, the first account comes from `claimInstance` or an OIDC provider's callback, and from nothing else. Until then no link is emailed.
85
- - One claim wins, across processes. Refusals are `FORBIDDEN` or `CONFLICT` with a `SetupRefusal` as `extensions.reason`. `asSetupRefusal` turns better-auth's own error into the same.
85
+ - One claim wins, across processes. A claim keeps others out for `SETUP_DEFAULTS.claimSeconds` (60), or `signInPlugins({ claimSeconds })`, should its process die part way. Refusals are `FORBIDDEN` or `CONFLICT` with a `SetupRefusal` as `extensions.reason`. `asSetupRefusal` turns better-auth's own error into the same.
86
86
  - A server for one person refuses the second account in its own `user.create.before`, which runs after the kit's.
87
87
  - `canPair` has to check that there is no account as well: `gate.isAdmitted()` only says the caller has the code.
88
88
  - A made-up code is the process's own, so run one process, or set `SETUP_CODE`.
@@ -25,7 +25,7 @@ stopOnSignals(server, { before: () => scheduler.stop(), after: closeDatabase });
25
25
 
26
26
  - Mount `/healthz` and `mountAuthRedirects` before the static handler, which answers every path.
27
27
  - `checkHealth` logs why Postgres did not answer and never says it: anyone may ask, and a driver's error names hosts.
28
- - `createStaticHandler` keeps `/assets/` and `/_expo/` files for a year, and answers 404 for one that is gone. Anything else that is not a file is `index.html`.
28
+ - `createStaticHandler` keeps `/assets/` and `/_expo/` files for a year (`createStaticHandler(dir, { immutableCacheSeconds })` changes that), and answers 404 for one that is gone. Anything else that is not a file is `index.html`.
29
29
  - `stopOnSignals` drains, runs `after`, and exits within `shutdownDeadlineSeconds`, under Docker's 10. A second signal exits at once.
30
30
  - `cutOff` runs at the drain deadline and is awaited before the open connections are cut: end SSE streams there, so a client reads a clean end instead of a reset.
31
31
  - `oidcSignInUrl` and `oidcRedirectUri` name the two OIDC routes for a provider.
@@ -29,4 +29,5 @@ checkMcpBudget(async () => (await client.listTools()).tools);
29
29
  - `contextFromRequest` takes the context factory /graphql uses, so a key or a session means the same on both doors.
30
30
  - `toolOptions` selects one level, allows an explicit null on writes only, drops filters and orders on other tables, and reads read-only and destructive hints from the create, update and delete prefixes. An option written after the spread replaces it.
31
31
  - `hints` are keyed by the MCP name (`create_task`), and `include` by the field (`Mutation.createTask`).
32
+ - `mcpEndpoint(names, { endpoint, version, description, auth? })` is the door's AI Catalog entry and Server Card, named by `discoveryNames` from `/discovery` (09-discovery.md). It needs `@cubicecho/mcp-discovery`, an optional peer.
32
33
  - `checkMcpBudget` holds one tool to `MCP_DEFAULTS.maxToolSchemaChars` and the listing to `maxToolListChars`. List through a real client, as an agent would.
@@ -0,0 +1,29 @@
1
+ # Discovery
2
+
3
+ `@cubicecho/server-kit/discovery` names a server the way every cubicecho server is named, lists its GraphQL API in its services document, and keeps its `_graphql._tcp` and `_mcp._tcp` announcements in step with a switch the app owns. It needs `@cubicecho/graphql-mdns-discovery`, an optional peer, and `bonjour-service` to announce. The MCP card is `mcpEndpoint`, in `/mcp`.
4
+
5
+ ```ts
6
+ import { graphqlDiscoveryMiddleware } from '@cubicecho/graphql-mdns-discovery';
7
+ import { discoveryMiddleware } from '@cubicecho/mcp-discovery';
8
+ import { createLanAdvertiser, discoveryNames, graphqlEndpoint } from '@cubicecho/server-kit/discovery';
9
+ import { mcpEndpoint } from '@cubicecho/server-kit/mcp';
10
+
11
+ const names = discoveryNames({ app: 'shop', title: 'Shop' });
12
+ app.use(graphqlDiscoveryMiddleware(() => [graphqlEndpoint(names, { version, auth: 'Bearer <API key>' })]));
13
+ app.use(discoveryMiddleware(() => [mcpEndpoint(names, { endpoint: 'shop', version, description: 'The shop.' })]));
14
+
15
+ const advertiser = createLanAdvertiser({
16
+ isWanted: () => settings.mdnsAdvertise,
17
+ options: () => ({ name: names.instance, port, mcpPath: '/mcp' }),
18
+ log: (message) => console.log(`[discovery] ${message}`),
19
+ });
20
+ server.listen(port, '0.0.0.0', () => void advertiser.sync());
21
+ ```
22
+
23
+ - `discoveryNames({ app, title, host?, repository? })` gives `instance` (`Shop on nas`), `slug`, `publisher` (`nas.shop`), `repository` (`https://github.com/cubicecho/<app>`) and `serviceName(endpoint)` (`io.github.cubicecho.shop.nas/<endpoint>`). `host` is `os.hostname()` unless given.
24
+ - `graphqlEndpoint(names, { path?, endpoint?, version?, description?, auth?, fields? })` is one entry for `graphqlDiscoveryMiddleware`. `path` is `/graphql` and `endpoint` `graphql` unless given. `auth` describes the `Authorization` header; the value is never in the document. `fields(context)` adds per-request fields, such as subscriptions, and wins over the rest.
25
+ - `mcpEndpoint(names, { path?, endpoint, version, description, auth? })`, from `/mcp`, is one entry for mcp-discovery's `discoveryMiddleware`, with a Server Card whose remote is the URL the request came in on. It needs `@cubicecho/mcp-discovery`.
26
+ - `createLanAdvertiser({ isWanted, options, log, announce? })` announces `_graphql._tcp` and, when `options()` has an `mcpPath`, `_mcp._tcp`, under one name and port. `isWanted` is read on every `sync()`, `options` when an announcement starts. A failed announcement is logged and retried on the next `sync()`. It loads mcp-discovery only to announce an MCP door, and logs how to install it when it is missing. `announce` replaces each type's announcer, for tests.
27
+ - `close()` stops both. Call it first in `stopOnSignals`'s `before`.
28
+ - The kit reads no environment: where the switch lives is the app's choice.
29
+ - Keep one copy of `@cubicecho/discovery-core` (`npm ls @cubicecho/discovery-core`). Two copies are two mDNS responders, and stopping one withdraws the other's address records.
@@ -1,5 +1,5 @@
1
1
  import { oidcPairingPlugins } from '@cubicecho/better-auth-oidc-pairing';
2
- import { type AuthPaths, type AuthSettings } from './defaults.ts';
2
+ import { type AuthPaths, type AuthSettings, type SetupSettings } from './defaults.ts';
3
3
  import { type SetupGate } from './setup.ts';
4
4
  /** What delivering one sign-in link is given. */
5
5
  export interface MagicLink {
@@ -11,7 +11,7 @@ export interface MagicLink {
11
11
  /** OIDC sign-in and pairing, without the two URLs, which follow from `appUrl`. */
12
12
  export type OidcOptions = Omit<Parameters<typeof oidcPairingPlugins>[0], 'signedInURL' | 'errorURL'>;
13
13
  /** What an app gives `signInPlugins`, besides OIDC. */
14
- export interface SignInOptions extends Partial<Pick<AuthSettings, 'magicLinkTtlMinutes'>> {
14
+ export interface SignInOptions extends Partial<Pick<AuthSettings, 'magicLinkTtlMinutes'>>, Partial<Pick<SetupSettings, 'claimSeconds'>> {
15
15
  /** Where users reach the app. */
16
16
  appUrl: string;
17
17
  /** Delivers a sign-in link, or undefined on an instance that cannot email. */
@@ -31,7 +31,7 @@ export interface SignInOptions extends Partial<Pick<AuthSettings, 'magicLinkTtlM
31
31
  * @param options - The app's links.
32
32
  * @returns The plugins.
33
33
  */
34
- declare function linkPlugins({ appUrl, deliver, paths, setup, magicLinkTtlMinutes, }: SignInOptions): ({
34
+ declare function linkPlugins({ appUrl, deliver, paths, setup, magicLinkTtlMinutes, claimSeconds, }: SignInOptions): ({
35
35
  id: "bearer";
36
36
  version: string;
37
37
  hooks: {
@@ -11,7 +11,7 @@ const MAGIC_LINK_PLUGIN_ID = 'magic-link';
11
11
  * @param options - The app's links.
12
12
  * @returns The plugins.
13
13
  */
14
- function linkPlugins({ appUrl, deliver, paths, setup, magicLinkTtlMinutes = AUTH_DEFAULTS.magicLinkTtlMinutes, }) {
14
+ function linkPlugins({ appUrl, deliver, paths, setup, magicLinkTtlMinutes = AUTH_DEFAULTS.magicLinkTtlMinutes, claimSeconds, }) {
15
15
  const { verify } = { ...AUTH_PATHS, ...paths };
16
16
  const links = deliver === undefined
17
17
  ? []
@@ -28,7 +28,7 @@ function linkPlugins({ appUrl, deliver, paths, setup, magicLinkTtlMinutes = AUTH
28
28
  },
29
29
  }),
30
30
  ];
31
- const setups = setup === undefined ? [] : [setupPlugin(setup)];
31
+ const setups = setup === undefined ? [] : [setupPlugin(setup, claimSeconds === undefined ? {} : { claimSeconds })];
32
32
  return [bearer(), ...links, ...setups];
33
33
  }
34
34
  /**
@@ -25,7 +25,7 @@ export declare function openAdmin(isProduction: boolean): OpenAdmin;
25
25
  *
26
26
  * @param url - The connection string.
27
27
  * @returns Both.
28
- * @throws {@link DatabaseBootError} If it names no database.
28
+ * @throws {@link DatabaseBootError} If it is not a URL, or names no database.
29
29
  */
30
30
  export declare function maintenanceTarget(url: string): MaintenanceTarget;
31
31
  /**
package/dist/db/create.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { PgDialect } from 'drizzle-orm/pg-core';
2
2
  import postgres from 'postgres';
3
3
  import { connectionOptions } from './connection.js';
4
- import { DatabaseBootError, errorCode } from './errors.js';
4
+ import { DatabaseBootError, errorCode, parseDatabaseUrl } from './errors.js';
5
5
  /** CREATE DATABASE lost a race with another instance doing the same. */
6
6
  const ALREADY_EXISTS = '42P04';
7
7
  /** The role may not create databases. */
@@ -23,14 +23,14 @@ export function openAdmin(isProduction) {
23
23
  *
24
24
  * @param url - The connection string.
25
25
  * @returns Both.
26
- * @throws {@link DatabaseBootError} If it names no database.
26
+ * @throws {@link DatabaseBootError} If it is not a URL, or names no database.
27
27
  */
28
28
  export function maintenanceTarget(url) {
29
- const parsed = new URL(url);
29
+ const parsed = parseDatabaseUrl(url);
30
30
  // Undecoded, as postgres-js reads it. Without one it falls back to the environment, which is not read here.
31
31
  const database = parsed.pathname.slice(1);
32
32
  if (database === '') {
33
- throw new DatabaseBootError('DATABASE_URL names no database, so there is nothing to create.');
33
+ throw new DatabaseBootError('DATABASE_URL names no database, so there is nothing to create. Add its name as the path: postgres://user:password@host:5432/<database>.');
34
34
  }
35
35
  parsed.pathname = `/${MAINTENANCE_DATABASE}`;
36
36
  return { database, maintenanceUrl: parsed.toString() };
@@ -2,6 +2,14 @@
2
2
  export declare class DatabaseBootError extends Error {
3
3
  name: string;
4
4
  }
5
+ /**
6
+ * Parses a connection string, refusing one that is not a URL without repeating it: it holds the password.
7
+ *
8
+ * @param url - The connection string.
9
+ * @returns The parsed URL.
10
+ * @throws {@link DatabaseBootError} If it does not parse. Node's own error would carry the whole string.
11
+ */
12
+ export declare function parseDatabaseUrl(url: string): URL;
5
13
  /**
6
14
  * Reads the driver or errno code of an error, or of whatever caused it.
7
15
  *
package/dist/db/errors.js CHANGED
@@ -2,6 +2,19 @@
2
2
  export class DatabaseBootError extends Error {
3
3
  name = 'DatabaseBootError';
4
4
  }
5
+ /**
6
+ * Parses a connection string, refusing one that is not a URL without repeating it: it holds the password.
7
+ *
8
+ * @param url - The connection string.
9
+ * @returns The parsed URL.
10
+ * @throws {@link DatabaseBootError} If it does not parse. Node's own error would carry the whole string.
11
+ */
12
+ export function parseDatabaseUrl(url) {
13
+ if (URL.canParse(url) === false) {
14
+ throw new DatabaseBootError('DATABASE_URL is not a valid URL. Percent-encode any character in the user or password that is not a letter, a digit or one of - . _ ~');
15
+ }
16
+ return new URL(url);
17
+ }
5
18
  /**
6
19
  * Reads the driver or errno code of an error, or of whatever caused it.
7
20
  *
@@ -1,5 +1,5 @@
1
1
  import { createDatabase, maintenanceTarget, openAdmin } from './create.js';
2
- import { DatabaseBootError, errorCode } from './errors.js';
2
+ import { DatabaseBootError, errorCode, parseDatabaseUrl } from './errors.js';
3
3
  import { requirePostgres } from './version.js';
4
4
  import { isStillStarting, waitForDatabase } from './wait.js';
5
5
  /** Postgres's answer when the database a connection names does not exist. */
@@ -66,9 +66,10 @@ async function waitOrCreate(db, { url, settings, needs, log, open }) {
66
66
  * @param url - The connection string.
67
67
  * @param code - Why, as the driver put it.
68
68
  * @returns The message.
69
+ * @throws {@link DatabaseBootError} If the connection string is not a URL.
69
70
  */
70
71
  function unreachable(url, code) {
71
- const { hostname, port } = new URL(url);
72
+ const { hostname, port } = parseDatabaseUrl(url);
72
73
  return (`Cannot reach Postgres at ${hostname}:${port || DEFAULT_POSTGRES_PORT} (${code}). ` +
73
74
  'Check DATABASE_URL, and that the database is up and reachable from here. With a remote Docker daemon, a port ' +
74
75
  "published on 127.0.0.1 is on the daemon host's loopback.");
@@ -17,6 +17,6 @@ export interface PostgresNeeds {
17
17
  * @param [needs] - What the app needs besides the minimum version.
18
18
  * @param [log] - Called with a warning when the server is newer than the app is tested on.
19
19
  * @returns Resolves once the server is known to be good enough.
20
- * @throws {@link DatabaseBootError} If it is too old, or lacks an extension.
20
+ * @throws {@link DatabaseBootError} If its version can't be read, it is too old, or it lacks an extension.
21
21
  */
22
22
  export declare function requirePostgres(db: Queryable, { extensions, testedMajor }?: PostgresNeeds, log?: (message: string) => void): Promise<void>;
@@ -23,11 +23,16 @@ async function rowsOf(db, query) {
23
23
  * @param [needs] - What the app needs besides the minimum version.
24
24
  * @param [log] - Called with a warning when the server is newer than the app is tested on.
25
25
  * @returns Resolves once the server is known to be good enough.
26
- * @throws {@link DatabaseBootError} If it is too old, or lacks an extension.
26
+ * @throws {@link DatabaseBootError} If its version can't be read, it is too old, or it lacks an extension.
27
27
  */
28
28
  export async function requirePostgres(db, { extensions = [], testedMajor = TESTED_POSTGRES_MAJOR } = {}, log = console.warn) {
29
29
  const [server] = await rowsOf(db, sql `select current_setting('server_version_num')::int as number, current_setting('server_version') as name`);
30
30
  const major = Math.floor(Number(server?.number) / VERSION_NUM_PER_MAJOR);
31
+ // An answer this can't read is refused: letting it through would skip the check it is here for.
32
+ const isKnown = Number.isFinite(major);
33
+ if (isKnown === false) {
34
+ throw new DatabaseBootError('Could not read the Postgres server version, so it cannot be checked. Nothing was changed. Check that DATABASE_URL points at Postgres.');
35
+ }
31
36
  if (major < MIN_POSTGRES_MAJOR) {
32
37
  throw new DatabaseBootError(`Postgres ${server?.name} is too old: ${MIN_POSTGRES_MAJOR} or later is needed. Nothing was changed.`);
33
38
  }
@@ -0,0 +1,58 @@
1
+ import type { Advertisement, Advertiser } from '@cubicecho/graphql-mdns-discovery/mdns';
2
+ /** What one announcement is started with. */
3
+ export interface Announcement {
4
+ name: string;
5
+ port: number;
6
+ /** Where the service is served. Each package has its own default when it is missing. */
7
+ path?: string;
8
+ tls?: boolean;
9
+ onError?: (error: Error) => void;
10
+ }
11
+ /** Starts one announcement. */
12
+ export type Announce = (announcement: Announcement) => Promise<Advertisement>;
13
+ /** What is announced, read each time an announcement starts. */
14
+ export interface LanAdvertisement {
15
+ /** The instance name, from `discoveryNames(...).instance`. */
16
+ name: string;
17
+ port: number;
18
+ /**
19
+ * Where the GraphQL API is served.
20
+ *
21
+ * @defaultValue `/graphql`
22
+ */
23
+ graphqlPath?: string;
24
+ /** Where the MCP door is served. Leave it out, and `_mcp._tcp` is not announced and mcp-discovery never loaded. */
25
+ mcpPath?: string;
26
+ /** Whether the host speaks HTTPS itself. */
27
+ tls?: boolean;
28
+ }
29
+ /** What the advertiser needs from the server. */
30
+ export interface LanAdvertiserDeps {
31
+ /**
32
+ * Whether the server is announced, read on every `sync`. The server decides where the switch lives (an env var, a
33
+ * settings row) and calls `sync` again when it changes.
34
+ */
35
+ isWanted: () => boolean;
36
+ /** What to announce. */
37
+ options: () => LanAdvertisement;
38
+ /** Told when an announcement starts or stops, and why one could not start. */
39
+ log: (message: string) => void;
40
+ /** Replaces how each service type is announced. For tests. */
41
+ announce?: {
42
+ graphql?: Announce;
43
+ mcp?: Announce;
44
+ };
45
+ }
46
+ /**
47
+ * Keeps a server's `_graphql._tcp` announcement, and its `_mcp._tcp` one when it has an MCP door, in step with the
48
+ * server's own switch.
49
+ *
50
+ * @param deps - The switch, what to announce, and the log.
51
+ * @returns `sync()`, called after `listen` and whenever the switch changes, and `close()`, called in `stopOnSignals`'s
52
+ * `before`.
53
+ *
54
+ * @remarks
55
+ * Both announcements go out under one instance name and port, through the one mDNS responder the discovery packages
56
+ * share. One that fails is logged and the server carries on; the next `sync` tries again.
57
+ */
58
+ export declare function createLanAdvertiser(deps: LanAdvertiserDeps): Advertiser;
@@ -0,0 +1,81 @@
1
+ import { DEFAULT_GRAPHQL_PATH } from '@cubicecho/graphql-mdns-discovery';
2
+ import { advertiseGraphql, createGraphqlAdvertiser } from '@cubicecho/graphql-mdns-discovery/mdns';
3
+ /** What an app installs to announce its MCP door. */
4
+ const MCP_DISCOVERY = '@cubicecho/mcp-discovery';
5
+ /**
6
+ * Announces an MCP door through mcp-discovery, loaded on first use so a server without one never needs it.
7
+ *
8
+ * @param announcement - What to announce.
9
+ * @returns The announcement.
10
+ * @throws When mcp-discovery is not installed, saying how to install it.
11
+ */
12
+ const announceMcp = async (announcement) => {
13
+ let mdns;
14
+ try {
15
+ mdns = await import('@cubicecho/mcp-discovery/mdns');
16
+ }
17
+ catch (cause) {
18
+ throw new Error(`Announcing an MCP door needs ${MCP_DISCOVERY}: npm install ${MCP_DISCOVERY}`, { cause });
19
+ }
20
+ return mdns.advertise(announcement);
21
+ };
22
+ /**
23
+ * Builds one service type's advertiser. Both use graphql-mdns-discovery's, which takes any start function, so an MCP
24
+ * door is kept in step the same way without loading mcp-discovery until it starts.
25
+ *
26
+ * @param deps - The server's switch and log.
27
+ * @param type - This type: its label for the log, whether the server has it, what to announce and how.
28
+ * @param type.label - Put before each log line, so the two types' lines can be told apart.
29
+ * @param type.isServed - Whether the server serves this type at all.
30
+ * @param type.options - What to announce.
31
+ * @param type.start - Starts this type's announcement.
32
+ * @returns The advertiser.
33
+ */
34
+ function typeAdvertiser(deps, type) {
35
+ return createGraphqlAdvertiser({
36
+ isWanted: () => deps.isWanted() && type.isServed(),
37
+ options: type.options,
38
+ log: (message) => deps.log(`${type.label}: ${message}`),
39
+ start: type.start,
40
+ });
41
+ }
42
+ /**
43
+ * Keeps a server's `_graphql._tcp` announcement, and its `_mcp._tcp` one when it has an MCP door, in step with the
44
+ * server's own switch.
45
+ *
46
+ * @param deps - The switch, what to announce, and the log.
47
+ * @returns `sync()`, called after `listen` and whenever the switch changes, and `close()`, called in `stopOnSignals`'s
48
+ * `before`.
49
+ *
50
+ * @remarks
51
+ * Both announcements go out under one instance name and port, through the one mDNS responder the discovery packages
52
+ * share. One that fails is logged and the server carries on; the next `sync` tries again.
53
+ */
54
+ export function createLanAdvertiser(deps) {
55
+ const graphql = typeAdvertiser(deps, {
56
+ label: 'GraphQL',
57
+ isServed: () => true,
58
+ options: () => {
59
+ const { name, port, graphqlPath = DEFAULT_GRAPHQL_PATH, tls } = deps.options();
60
+ return { name, port, path: graphqlPath, tls };
61
+ },
62
+ start: deps.announce?.graphql ?? advertiseGraphql,
63
+ });
64
+ const mcp = typeAdvertiser(deps, {
65
+ label: 'MCP',
66
+ isServed: () => deps.options().mcpPath !== undefined,
67
+ options: () => {
68
+ const { name, port, mcpPath, tls } = deps.options();
69
+ return { name, port, path: mcpPath, tls };
70
+ },
71
+ start: deps.announce?.mcp ?? announceMcp,
72
+ });
73
+ return {
74
+ sync: async () => {
75
+ await Promise.all([graphql.sync(), mcp.sync()]);
76
+ },
77
+ close: async () => {
78
+ await Promise.all([graphql.close(), mcp.close()]);
79
+ },
80
+ };
81
+ }
@@ -0,0 +1,40 @@
1
+ import { type AdvertisedGraphqlApi, type GraphqlServiceContext, type GraphqlServiceDraft } from '@cubicecho/graphql-mdns-discovery';
2
+ import type { DiscoveryNames } from './names.ts';
3
+ /** What a server's GraphQL entry says besides its names. */
4
+ export interface GraphqlEndpointOptions {
5
+ /**
6
+ * Where the API is served.
7
+ *
8
+ * @defaultValue `/graphql`
9
+ */
10
+ path?: string;
11
+ /**
12
+ * The endpoint's stable name under the host, the last part of its service name.
13
+ *
14
+ * @defaultValue `graphql`
15
+ */
16
+ endpoint?: string;
17
+ /** The app's release. */
18
+ version?: string;
19
+ /** One line on what the API is. */
20
+ description?: string;
21
+ /**
22
+ * What a client puts in `Authorization`, never the value itself, such as `Bearer <session token or API key>`.
23
+ * Leave it out for an API anyone may call.
24
+ */
25
+ auth?: string;
26
+ /**
27
+ * Anything else the entry says, read per request, such as its subscriptions or `schemaUrl`. It wins over the rest.
28
+ *
29
+ * @param context - The request's origin and the API's URL on it.
30
+ */
31
+ fields?: (context: GraphqlServiceContext) => Partial<GraphqlServiceDraft>;
32
+ }
33
+ /**
34
+ * Builds the entry for a server's GraphQL API in its services document.
35
+ *
36
+ * @param names - The server's names, from `discoveryNames`.
37
+ * @param [options] - The path, the endpoint's name, and what the entry says.
38
+ * @returns The entry, for `graphqlDiscoveryMiddleware(() => [entry])`.
39
+ */
40
+ export declare function graphqlEndpoint(names: DiscoveryNames, options?: GraphqlEndpointOptions): AdvertisedGraphqlApi;
@@ -0,0 +1,24 @@
1
+ import { DEFAULT_GRAPHQL_PATH, } from '@cubicecho/graphql-mdns-discovery';
2
+ /**
3
+ * Builds the entry for a server's GraphQL API in its services document.
4
+ *
5
+ * @param names - The server's names, from `discoveryNames`.
6
+ * @param [options] - The path, the endpoint's name, and what the entry says.
7
+ * @returns The entry, for `graphqlDiscoveryMiddleware(() => [entry])`.
8
+ */
9
+ export function graphqlEndpoint(names, options = {}) {
10
+ const { path = DEFAULT_GRAPHQL_PATH, endpoint = 'graphql', version, description, auth, fields } = options;
11
+ return {
12
+ path,
13
+ service: (context) => ({
14
+ name: names.serviceName(endpoint),
15
+ title: names.instance,
16
+ ...(version === undefined ? {} : { version }),
17
+ ...(description === undefined ? {} : { description }),
18
+ ...(auth === undefined
19
+ ? {}
20
+ : { headers: [{ name: 'Authorization', description: auth, isRequired: true, isSecret: true }] }),
21
+ ...fields?.(context),
22
+ }),
23
+ };
24
+ }
@@ -0,0 +1,3 @@
1
+ export { type Announce, type Announcement, createLanAdvertiser, type LanAdvertisement, type LanAdvertiserDeps, } from './advertiser.ts';
2
+ export { type GraphqlEndpointOptions, graphqlEndpoint } from './graphql.ts';
3
+ export { type DiscoveryNames, type DiscoveryNamesOptions, discoveryNames, type SourceRepository } from './names.ts';
@@ -0,0 +1,3 @@
1
+ export { createLanAdvertiser, } from './advertiser.js';
2
+ export { graphqlEndpoint } from './graphql.js';
3
+ export { discoveryNames } from './names.js';
@@ -0,0 +1,51 @@
1
+ /** Where an app's source lives. */
2
+ export interface SourceRepository {
3
+ url: string;
4
+ source: string;
5
+ }
6
+ /** What a server's names are built from. */
7
+ export interface DiscoveryNamesOptions {
8
+ /** The app's package and repository name, such as `ai-router`. */
9
+ app: string;
10
+ /** What people call it, such as `AI Router`. The instance name is this "on" the host. */
11
+ title: string;
12
+ /**
13
+ * The machine's hostname, which keeps two copies of the app on one network apart.
14
+ *
15
+ * @defaultValue `os.hostname()`
16
+ */
17
+ host?: string;
18
+ /**
19
+ * Where its source lives.
20
+ *
21
+ * @defaultValue `https://github.com/cubicecho/<app>` on GitHub
22
+ */
23
+ repository?: SourceRepository;
24
+ }
25
+ /** The names one server advertises under, the same for its GraphQL API and its MCP door. */
26
+ export interface DiscoveryNames {
27
+ app: string;
28
+ title: string;
29
+ host: string;
30
+ /** The host, as a DNS label. */
31
+ slug: string;
32
+ /** The mDNS instance name, such as `AI Router on nas`. A server that watches the network skips its own. */
33
+ instance: string;
34
+ /** The `urn:air` publisher of its MCP endpoints, such as `nas.ai-router`. */
35
+ publisher: string;
36
+ repository: SourceRepository;
37
+ /**
38
+ * Names one endpoint, such as `io.github.cubicecho.ai-router.nas/agents`.
39
+ *
40
+ * @param endpoint - The endpoint's stable name under the host.
41
+ * @returns The reverse-DNS name, with exactly one slash.
42
+ */
43
+ serviceName: (endpoint: string) => string;
44
+ }
45
+ /**
46
+ * Builds the names a server advertises under, so every app names itself the same way.
47
+ *
48
+ * @param options - The app, its title, and optionally the hostname and repository.
49
+ * @returns The names.
50
+ */
51
+ export declare function discoveryNames(options: DiscoveryNamesOptions): DiscoveryNames;
@@ -0,0 +1,26 @@
1
+ import { hostname } from 'node:os';
2
+ import { hostSlug } from '@cubicecho/graphql-mdns-discovery';
3
+ /** The reverse-DNS namespace every cubicecho service name starts with. */
4
+ const NAMESPACE = 'io.github.cubicecho';
5
+ /** Where a cubicecho app's source lives, shown on what it advertises. */
6
+ const GITHUB = 'https://github.com/cubicecho';
7
+ /**
8
+ * Builds the names a server advertises under, so every app names itself the same way.
9
+ *
10
+ * @param options - The app, its title, and optionally the hostname and repository.
11
+ * @returns The names.
12
+ */
13
+ export function discoveryNames(options) {
14
+ const { app, title, host = hostname() } = options;
15
+ const slug = hostSlug(host);
16
+ return {
17
+ app,
18
+ title,
19
+ host,
20
+ slug,
21
+ instance: `${title} on ${host}`,
22
+ publisher: `${slug}.${app}`,
23
+ repository: options.repository ?? { url: `${GITHUB}/${app}`, source: 'github' },
24
+ serviceName: (endpoint) => `${NAMESPACE}.${app}.${slug}/${endpoint}`,
25
+ };
26
+ }
@@ -1,13 +1,15 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { type HttpSettings } from './defaults.ts';
2
3
  /** A request handler, for Express or plain `node:http`. */
3
4
  export type StaticHandler = (request: IncomingMessage, response: ServerResponse) => void;
4
5
  /**
5
6
  * Serves a built single-page app, whose `index.html` answers every path that is not a file.
6
7
  *
7
8
  * @param root - The directory holding the built app.
9
+ * @param [overrides] - How long a browser keeps a hashed file, when not `HTTP_DEFAULTS.immutableCacheSeconds`.
8
10
  * @returns The handler.
9
11
  *
10
12
  * @remarks
11
13
  * A hashed file that is missing is a 404, never the index: a browser would keep that page under the bundle's name.
12
14
  */
13
- export declare function createStaticHandler(root: string): StaticHandler;
15
+ export declare function createStaticHandler(root: string, overrides?: Partial<Pick<HttpSettings, 'immutableCacheSeconds'>>): StaticHandler;
@@ -50,13 +50,15 @@ function isFileAt(path) {
50
50
  * Serves a built single-page app, whose `index.html` answers every path that is not a file.
51
51
  *
52
52
  * @param root - The directory holding the built app.
53
+ * @param [overrides] - How long a browser keeps a hashed file, when not `HTTP_DEFAULTS.immutableCacheSeconds`.
53
54
  * @returns The handler.
54
55
  *
55
56
  * @remarks
56
57
  * A hashed file that is missing is a 404, never the index: a browser would keep that page under the bundle's name.
57
58
  */
58
- export function createStaticHandler(root) {
59
+ export function createStaticHandler(root, overrides = {}) {
59
60
  const rootDir = resolve(root);
61
+ const immutableCacheSeconds = overrides.immutableCacheSeconds ?? HTTP_DEFAULTS.immutableCacheSeconds;
60
62
  return (request, response) => {
61
63
  const isRead = request.method === 'GET' || request.method === 'HEAD';
62
64
  if (isRead === false) {
@@ -86,7 +88,7 @@ export function createStaticHandler(root) {
86
88
  }
87
89
  const headers = {
88
90
  'content-type': CONTENT_TYPES[extname(filePath)] ?? UNKNOWN_TYPE,
89
- 'cache-control': isHashed ? `public, max-age=${HTTP_DEFAULTS.immutableCacheSeconds}, immutable` : 'no-cache',
91
+ 'cache-control': isHashed ? `public, max-age=${immutableCacheSeconds}, immutable` : 'no-cache',
90
92
  'x-content-type-options': 'nosniff',
91
93
  };
92
94
  if (request.method === 'HEAD') {
@@ -0,0 +1,30 @@
1
+ import { type AdvertisedEndpoint } from '@cubicecho/mcp-discovery';
2
+ import type { DiscoveryNames } from '../discovery/names.ts';
3
+ /** What a server's MCP card says besides its names. */
4
+ export interface McpEndpointOptions {
5
+ /**
6
+ * Where the door is served.
7
+ *
8
+ * @defaultValue `/mcp`
9
+ */
10
+ path?: string;
11
+ /** The endpoint's stable name under the host, the last part of its card name and `urn:air` id, such as `agents`. */
12
+ endpoint: string;
13
+ /** The app's release, the card's version. */
14
+ version: string;
15
+ /** What the door offers, in at most 100 characters. Cards are public: name no data behind it. */
16
+ description: string;
17
+ /**
18
+ * What a client puts in `Authorization`, never the value itself, such as `Bearer <workspace key>`. Leave it out for
19
+ * a door anyone may call.
20
+ */
21
+ auth?: string;
22
+ }
23
+ /**
24
+ * Builds the AI Catalog entry for a server's MCP door, with its Server Card.
25
+ *
26
+ * @param names - The server's names, from `discoveryNames` in `@cubicecho/server-kit/discovery`.
27
+ * @param options - The path, the endpoint's name, the version and what the card says.
28
+ * @returns The entry, for `discoveryMiddleware(() => [entry])`. Its card names the URL the request came in on.
29
+ */
30
+ export declare function mcpEndpoint(names: DiscoveryNames, options: McpEndpointOptions): AdvertisedEndpoint;
@@ -0,0 +1,24 @@
1
+ import { airIdentifier, createServerCard, TRANSPORT_STREAMABLE_HTTP, } from '@cubicecho/mcp-discovery';
2
+ /**
3
+ * Builds the AI Catalog entry for a server's MCP door, with its Server Card.
4
+ *
5
+ * @param names - The server's names, from `discoveryNames` in `@cubicecho/server-kit/discovery`.
6
+ * @param options - The path, the endpoint's name, the version and what the card says.
7
+ * @returns The entry, for `discoveryMiddleware(() => [entry])`. Its card names the URL the request came in on.
8
+ */
9
+ export function mcpEndpoint(names, options) {
10
+ const { path = '/mcp', endpoint, version, description, auth } = options;
11
+ const headers = auth === undefined ? undefined : [{ name: 'Authorization', description: auth, isRequired: true, isSecret: true }];
12
+ return {
13
+ path,
14
+ identifier: airIdentifier(names.publisher, endpoint),
15
+ card: ({ endpointUrl }) => createServerCard({
16
+ name: names.serviceName(endpoint),
17
+ version,
18
+ title: names.instance,
19
+ description,
20
+ repository: names.repository,
21
+ remotes: [{ type: TRANSPORT_STREAMABLE_HTTP, url: endpointUrl, ...(headers === undefined ? {} : { headers }) }],
22
+ }),
23
+ };
24
+ }
@@ -1,3 +1,4 @@
1
1
  export { MCP_DEFAULTS, type McpSettings } from './defaults.ts';
2
+ export { type McpEndpointOptions, mcpEndpoint } from './discovery.ts';
2
3
  export { contextFromRequest } from './request.ts';
3
4
  export { type SharedToolOptions, type ToolOptions, toolOptions } from './tool-options.ts';
package/dist/mcp/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { MCP_DEFAULTS } from './defaults.js';
2
+ export { mcpEndpoint } from './discovery.js';
2
3
  export { contextFromRequest } from './request.js';
3
4
  export { toolOptions } from './tool-options.js';
package/llms.txt CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  Agent-facing docs for @cubicecho/server-kit: one task or concept per page, then what each package.json "exports" entry exports. Generated from _agents/docs/ and the doc comments in src/ by @cubicecho/agent-docs; edit those, not this file.
6
6
 
7
- Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0 (optional), `@cubicecho/better-auth-oidc-pairing` ^1.1.0 (optional), `@cubicecho/graphql-mcp` ^3.1.0 (optional), `@electric-sql/pglite` ^0.5.0 (optional), `better-auth` >=1.7.28 <1.8.0 (optional), `drizzle-orm` 1.0.0-rc.5, `express` ^5.0.0, `graphql` ^16.0.0, `graphql-yoga` ^6.0.0, `postgres` ^3.4.0 || ^4.0.0 (optional), `vitest` ^5.0.0 (optional).
7
+ Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0 (optional), `@cubicecho/better-auth-oidc-pairing` ^1.1.0 (optional), `@cubicecho/graphql-mcp` ^3.1.0 (optional), `@cubicecho/graphql-mdns-discovery` ^1.2.0 (optional), `@cubicecho/mcp-discovery` >=0.7.0 <0.9.0 (optional), `@electric-sql/pglite` ^0.5.0 (optional), `better-auth` >=1.7.28 <1.8.0 (optional), `bonjour-service` ^1.4.0 (optional), `drizzle-orm` 1.0.0-rc.5, `express` ^5.0.0, `graphql` ^16.0.0, `graphql-yoga` ^6.0.0, `postgres` ^3.4.0 || ^4.0.0 (optional), `vitest` ^5.0.0 (optional).
8
8
 
9
9
  ## Docs
10
10
 
@@ -16,6 +16,7 @@ Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0 (optio
16
16
  - [HTTP](_agents/docs/06-http.md): `@cubicecho/server-kit/http` has what surrounds an Express app: a clean stop, the health check, serving the built app, and the two OIDC redirects.
17
17
  - [MCP](_agents/docs/07-mcp.md): `@cubicecho/server-kit/mcp` has what every MCP door over a drizzle-graphql schema shares: how the caller is read, and the options that keep the listing small. It needs `@cubicecho/graphql-mcp`, an optional peer.
18
18
  - [Database lock](_agents/docs/08-lock.md): `@cubicecho/server-kit/lock` makes one process the only one that uses a database, for an app that keeps what it serves in memory. It is a Postgres advisory lock held on a connection of its own. It needs no peer: the connection is a `pg.Client` the app makes.
19
+ - [Discovery](_agents/docs/09-discovery.md): `@cubicecho/server-kit/discovery` names a server the way every cubicecho server is named, lists its GraphQL API in its services document, and keeps its `_graphql._tcp` and `_mcp._tcp` announcements in step with a switch the app owns. It needs `@cubicecho/graphql-mdns-discovery`, an optional peer, and `bonjour-service` to announce. The MCP card is `mcpEndpoint`, in `/mcp`.
19
20
  - [Common mistakes](_agents/docs/common-mistakes.md): What goes wrong when the kit is wired up slightly differently, and the fix for each.
20
21
 
21
22
  ## Exports: @cubicecho/server-kit/auth
@@ -88,6 +89,20 @@ Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0 (optio
88
89
  - `Queryable` (type): Anything that can run a query: the Drizzle client on postgres-js, pg or PGlite.
89
90
  - `waitForDatabase`: Waits until Postgres answers a query.
90
91
 
92
+ ## Exports: @cubicecho/server-kit/discovery
93
+
94
+ - `Announce` (type): Starts one announcement.
95
+ - `Announcement` (type): What one announcement is started with.
96
+ - `createLanAdvertiser`: Keeps a server's `_graphql._tcp` announcement, and its `_mcp._tcp` one when it has an MCP door, in step with the server's own switch.
97
+ - `LanAdvertisement` (type): What is announced, read each time an announcement starts.
98
+ - `LanAdvertiserDeps` (type): What the advertiser needs from the server.
99
+ - `GraphqlEndpointOptions` (type): What a server's GraphQL entry says besides its names.
100
+ - `graphqlEndpoint`: Builds the entry for a server's GraphQL API in its services document.
101
+ - `DiscoveryNames` (type): The names one server advertises under, the same for its GraphQL API and its MCP door.
102
+ - `DiscoveryNamesOptions` (type): What a server's names are built from.
103
+ - `discoveryNames`: Builds the names a server advertises under, so every app names itself the same way.
104
+ - `SourceRepository` (type): Where an app's source lives.
105
+
91
106
  ## Exports: @cubicecho/server-kit/graphql
92
107
 
93
108
  - `OPERATION_LIMIT_DEFAULTS`: What `useOperationLimits` and an app's `buildSchema` use when the app overrides nothing.
@@ -145,6 +160,8 @@ Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0 (optio
145
160
 
146
161
  - `MCP_DEFAULTS`: What the MCP helpers and `checkMcpBudget` use when the app overrides nothing.
147
162
  - `McpSettings` (type): Bounds on the MCP door.
163
+ - `McpEndpointOptions` (type): What a server's MCP card says besides its names.
164
+ - `mcpEndpoint`: Builds the AI Catalog entry for a server's MCP door, with its Server Card.
148
165
  - `contextFromRequest`: Reads an MCP request's caller the way /graphql reads its own, so a credential means the same on both doors.
149
166
  - `SharedToolOptions` (type): The part of graphql-mcp's options that is the same for every schema drizzle-graphql generates.
150
167
  - `ToolOptions` (type): What an app says about its tools.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cubicecho/server-kit",
3
- "version": "0.10.0",
3
+ "version": "0.11.1",
4
4
  "description": "The server code every cubicecho GraphQL backend shares: database boot, id columns and the checks that keep a schema to the standard.",
5
5
  "license": "MIT",
6
6
  "author": "Benjamin Van Treese",
@@ -35,6 +35,10 @@
35
35
  "types": "./dist/db/index.d.ts",
36
36
  "import": "./dist/db/index.js"
37
37
  },
38
+ "./discovery": {
39
+ "types": "./dist/discovery/index.d.ts",
40
+ "import": "./dist/discovery/index.js"
41
+ },
38
42
  "./graphql": {
39
43
  "types": "./dist/graphql/index.d.ts",
40
44
  "import": "./dist/graphql/index.js"
@@ -79,8 +83,11 @@
79
83
  "@better-auth/sso": ">=1.7.28 <1.8.0",
80
84
  "@cubicecho/better-auth-oidc-pairing": "^1.1.0",
81
85
  "@cubicecho/graphql-mcp": "^3.1.0",
86
+ "@cubicecho/graphql-mdns-discovery": "^1.2.0",
87
+ "@cubicecho/mcp-discovery": ">=0.7.0 <0.9.0",
82
88
  "@electric-sql/pglite": "^0.5.0",
83
89
  "better-auth": ">=1.7.28 <1.8.0",
90
+ "bonjour-service": "^1.4.0",
84
91
  "drizzle-orm": "1.0.0-rc.5",
85
92
  "express": "^5.0.0",
86
93
  "graphql": "^16.0.0",
@@ -98,12 +105,21 @@
98
105
  "@cubicecho/graphql-mcp": {
99
106
  "optional": true
100
107
  },
108
+ "@cubicecho/graphql-mdns-discovery": {
109
+ "optional": true
110
+ },
111
+ "@cubicecho/mcp-discovery": {
112
+ "optional": true
113
+ },
101
114
  "@electric-sql/pglite": {
102
115
  "optional": true
103
116
  },
104
117
  "better-auth": {
105
118
  "optional": true
106
119
  },
120
+ "bonjour-service": {
121
+ "optional": true
122
+ },
107
123
  "postgres": {
108
124
  "optional": true
109
125
  },
@@ -117,6 +133,8 @@
117
133
  "@cubicecho/agent-docs": "^0.2.0",
118
134
  "@cubicecho/better-auth-oidc-pairing": "^1.1.0",
119
135
  "@cubicecho/graphql-mcp": "^3.2.0",
136
+ "@cubicecho/graphql-mdns-discovery": "^1.2.0",
137
+ "@cubicecho/mcp-discovery": "^0.8.0",
120
138
  "@electric-sql/pglite": "^0.5.17",
121
139
  "@modelcontextprotocol/sdk": "^1.32.2",
122
140
  "@semantic-release/changelog": "^6.0.3",
@@ -128,6 +146,7 @@
128
146
  "@types/express": "^5.0.6",
129
147
  "@types/node": "^24.19.4",
130
148
  "better-auth": "^1.7.28",
149
+ "bonjour-service": "^1.4.4",
131
150
  "drizzle-kit": "^1.0.0-rc.5",
132
151
  "drizzle-orm": "^1.0.0-rc.5",
133
152
  "express": "^5.3.0",
package/skill/SKILL.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: cubicecho-server-kit
3
- description: How to build, update or review a cubicecho GraphQL server on @cubicecho/server-kit, the shared server code and the one set of versions — which kit entry does which job (/db prepareDatabase and connectionOptions, /columns id() moment() timestamps() singleton(), /auth authPreset signInPlugins setup gate device links throttle, /graphql ErrorCode errors parseOrThrow useOperationLimits useIntrospectionGate graphqlLogger, /http stopOnSignals with its cutOff step checkHealth createStaticHandler mountAuthRedirects, /lock holdPostgresLock, /mcp toolOptions contextFromRequest, /testing checkSchemaConventions checkPostgresVersion checkMcpBudget), how an app wires each one into createApp and index.ts, UUIDv7 ids on Postgres 18, better-auth with OIDC sign-in and provider pairing by Dynamic Client Registration, the defaults groups the kit owns, and moving an existing server onto the kit. Load it whenever you touch a cubicecho backend's boot, database, auth, SSO, errors, limits, MCP door or tests, or the kit itself.
3
+ description: How to build, update or review a cubicecho GraphQL server on @cubicecho/server-kit, the shared server code and the one set of versions — which kit entry does which job (/db prepareDatabase and connectionOptions, /columns id() moment() timestamps() singleton(), /auth authPreset signInPlugins setup gate device links throttle, /graphql ErrorCode errors parseOrThrow useOperationLimits useIntrospectionGate graphqlLogger, /http stopOnSignals with its cutOff step checkHealth createStaticHandler mountAuthRedirects, /lock holdPostgresLock, /mcp toolOptions contextFromRequest mcpEndpoint, /discovery discoveryNames graphqlEndpoint createLanAdvertiser, /testing checkSchemaConventions checkPostgresVersion checkMcpBudget), how an app wires each one into createApp and index.ts, UUIDv7 ids on Postgres 18, better-auth with OIDC sign-in and provider pairing by Dynamic Client Registration, the defaults groups the kit owns, and moving an existing server onto the kit. Load it whenever you touch a cubicecho backend's boot, database, auth, SSO, errors, limits, MCP door or tests, or the kit itself.
4
4
  ---
5
5
 
6
6
  # cubicecho server kit
@@ -25,6 +25,7 @@ The kit's API reference ships in the package: `node_modules/@cubicecho/server-ki
25
25
  | OIDC sign-in and pairing a provider from a setup URL, who may pair, `mountAuthRedirects` | `/auth`, `/http` | [sso.md](sso.md), after auth.md |
26
26
  | Errors a client reads, `ErrorCode`, masking and the logger, zod with `parseOrThrow`, page size, depth and cost, who may introspect | `/graphql` | [graphql.md](graphql.md) |
27
27
  | The `/mcp` door: `toolOptions`, `contextFromRequest`, `MCP_DEFAULTS`, budgets | `/mcp` | [mcp.md](mcp.md) |
28
+ | Being found: the GraphQL services document, the MCP card, `_graphql._tcp` and `_mcp._tcp`, the server's switch | `/discovery`, `/mcp` | [discovery.md](discovery.md) |
28
29
  | A limit, timeout, size or lifetime: the kit's `<CONCEPT>_DEFAULTS` groups and the server's own | all | [defaults.md](defaults.md) |
29
30
  | The tests the kit registers, and the tests that hold what a server wires | `/testing` | [testing.md](testing.md) |
30
31
  | Putting an existing server on the kit, upgrading the kit, or changing the kit | — | [adopting.md](adopting.md) |
@@ -33,11 +34,11 @@ A new server needs the `cubicecho-backend` skill's archetype file, then boot, da
33
34
 
34
35
  ## Versions
35
36
 
36
- One set for every server. The kit has the singletons as peers, so npm refuses a server outside these ranges. What only one entry needs is an optional peer that the server installs itself: `postgres` for `/db`; `better-auth`, `@better-auth/sso` and `@cubicecho/better-auth-oidc-pairing` for `/auth`; `@cubicecho/graphql-mcp` for `/mcp`.
37
+ One set for every server. The kit has the singletons as peers, so npm refuses a server outside these ranges. What only one entry needs is an optional peer that the server installs itself: `postgres` for `/db`; `better-auth`, `@better-auth/sso` and `@cubicecho/better-auth-oidc-pairing` for `/auth`; `@cubicecho/graphql-mcp` and `@cubicecho/mcp-discovery` for `/mcp`; `@cubicecho/graphql-mdns-discovery` for `/discovery`; `bonjour-service` to announce.
37
38
 
38
39
  | Package | Version |
39
40
  |---|---|
40
- | `@cubicecho/server-kit` | ^0.9 |
41
+ | `@cubicecho/server-kit` | ^0.11 |
41
42
  | Node | 26 |
42
43
  | Postgres / PGlite (tests) | 18 or later / ^0.5 |
43
44
  | `drizzle-orm`, `drizzle-kit` | `1.0.0-rc.5`, exact |
@@ -50,6 +51,10 @@ One set for every server. The kit has the singletons as peers, so npm refuses a
50
51
  | `@cubicecho/better-auth-oidc-pairing` | ^1.1 |
51
52
  | `@cubicecho/graphql-better-auth` | ^1.1 |
52
53
  | `@cubicecho/graphql-mcp` (with `/mcp`) | ^3.1 |
54
+ | `@cubicecho/mcp-discovery` (with `/mcp`) | ^0.8 (0.7 is still accepted) |
55
+ | `@cubicecho/graphql-mdns-discovery` | ^1.2 |
56
+ | `@cubicecho/discovery-core` (through both) | ^1.1, one copy |
57
+ | `bonjour-service` (to announce or look) | ^1.4 |
53
58
  | `zod` | 4 |
54
59
  | `nodemailer` (an optional dependency) | ^10 |
55
60
  | `vitest` | 5 |
@@ -75,6 +80,7 @@ Each rule is stated once here; the file it names has the detail and the code.
75
80
  - **Codes everywhere.** A failure a client reads is a coded `GraphQLError` from the kit's helpers, a member of `ErrorCode`; everything else is masked by Yoga and logged by `graphqlLogger`. Rows the caller doesn't own are `NOT_FOUND`, never `FORBIDDEN`. Caught values are read with `errorMessage(error)`. See graphql.md.
76
81
  - **Every query is bounded**: `limits` and `complexity: true` in buildSchema, `useOperationLimits()` on every Yoga, and the `HTTP_DEFAULTS.bodyLimit` cap on `/graphql` and `/mcp`. See graphql.md and boot.md.
77
82
  - **Only who `allow` lets in introspects in production**: `useIntrospectionGate` on every Yoga, a person or nobody, never an app's key. See graphql.md.
83
+ - **Every server can be found, and announces only when it is told to.** It serves its GraphQL services document, and its MCP catalog with `/mcp`, named by `discoveryNames`. `createLanAdvertiser` announces on the server's own switch, off unless turned on. See discovery.md.
78
84
  - **Tunables live in `defaults.ts`.** A group the kit owns is overridden where the thing is built, never copied. See defaults.md.
79
85
  - **`/healthz` is `{ ok, version }`**, 503 when Postgres doesn't answer, and never says why. See boot.md.
80
86
  - **The kit's checks run in every server's tests**: `checkSchemaConventions`, `checkPostgresVersion`, and `checkMcpBudget` where there is `/mcp`. See testing.md.
package/skill/adopting.md CHANGED
@@ -31,6 +31,7 @@ Then replace the server's own copies, one concern per commit, with only that con
31
31
  | a connection-retry loop, `ssl` logic | `prepareDatabase`, `connectionOptions` | boot.md, in the Postgres 18 release |
32
32
  | hand-written id and timestamp columns | `id()`, `moment()`, `timestamps()` | database.md, in the Postgres 18 release |
33
33
  | `contextFromRequest`-like code for `/mcp`, its own budgets | `contextFromRequest`, `toolOptions`, `checkMcpBudget` | mcp.md |
34
+ | `discovery/endpoints.ts` building card names, `createAdvertiser` from mcp-discovery | `discoveryNames`, `mcpEndpoint`, `graphqlEndpoint`, `createLanAdvertiser` | discovery.md |
34
35
  | copies of the kit's defaults groups | overrides where the thing is built | defaults.md |
35
36
 
36
37
  **The Postgres 18 release goes last and is announced as breaking**: the move to 18, `prepareDatabase`, `id()` as the default, and the two schema tests together (database.md). `prepareDatabase` stops every instance still on 17, so it is never adopted before.
package/skill/auth.md CHANGED
@@ -112,7 +112,7 @@ export async function sessionUserId(auth: Auth, headers: Headers): Promise<strin
112
112
 
113
113
  - `createAuth` has no written return type: `auth.api`'s type is built from the plugin list. Keep the plugins one array literal, with `signInPlugins` spread into it.
114
114
  - **An option after the preset's spread replaces the preset's whole value**, so a `session: { … }` of your own repeats `expiresIn`. Never add `emailAndPassword`.
115
- - Lifetimes and page paths are `AUTH_DEFAULTS` and `AUTH_PATHS`; override through `sessionTtlDays`, `magicLinkTtlMinutes` or `paths`.
115
+ - Lifetimes and page paths are `AUTH_DEFAULTS` and `AUTH_PATHS`; override through `sessionTtlDays`, `magicLinkTtlMinutes` or `paths`. How long a setup claim keeps others out is `SETUP_DEFAULTS.claimSeconds`, overridden by `signInPlugins({ claimSeconds })`.
116
116
  - `secret`, `sendMagicLink` and `pinned` are dependencies, not settings, so they stay in `AuthOptions`.
117
117
  - `sendsMagicLinks(auth)` reads the instance, not `SMTP_URL`, so a test's captured links count as on.
118
118
  - `better-auth`, `@better-auth/sso` and `@cubicecho/better-auth-oidc-pairing` are the server's own dependencies, all three even with `oidc: false`.
package/skill/boot.md CHANGED
@@ -230,6 +230,7 @@ export function createGraphQLHandler(deps: ContextDeps) {
230
230
  - The Dockerfile's `CMD` stays in exec form, `["node", "server/src/index.ts"]`, so node gets the signal. `npm start` or `sh -c` swallow it.
231
231
  - Background work that `before` stops must tolerate being cut off mid-item: its queue lives in a table, so the next boot resumes it.
232
232
  - Register it before any long boot-time work (draining a queue), so a stop during that work still shuts down cleanly.
233
+ - A server that announces itself closes its `createLanAdvertiser` first in `before`, so the goodbye goes out while it still answers (discovery.md).
233
234
 
234
235
  ## One process per database
235
236
 
@@ -263,7 +264,7 @@ const releaseLock = await holdPostgresLock(session, {
263
264
  ## Health and static files
264
265
 
265
266
  - **`/healthz` answers `{ ok, version }` and never says why it is not ok.** Anyone may ask, and a driver's error names hosts. `checkHealth` round-trips to Postgres and logs the error with its cause, so monitoring that wants the reason reads the log.
266
- - `createStaticHandler` serves the built app: `/assets/` and `/_expo/` files are kept for a year, and one that is gone is a 404. Any other path that is not a file is `index.html`.
267
+ - `createStaticHandler` serves the built app: `/assets/` and `/_expo/` files are kept for a year (`HTTP_DEFAULTS.immutableCacheSeconds`, overridden as its second argument), and one that is gone is a 404. Any other path that is not a file is `index.html`.
267
268
  - **It answers every path**, so `/healthz`, `/mcp` and `mountAuthRedirects` are mounted before it.
268
269
 
269
270
  ## In a service
@@ -0,0 +1,130 @@
1
+ # Discovery on the LAN
2
+
3
+ How a server says what it serves and announces itself on the network: its GraphQL API in `/.well-known/graphql-services.json` and as `_graphql._tcp`, and its MCP door in the AI Catalog and as `_mcp._tcp`. A server that looks for others on the network (symphony's upstreams, ai-router's MCP servers) does that itself; the end of this file says how.
4
+
5
+ **Contents:** [What the kit does and the libraries do](#what-the-kit-does-and-the-libraries-do) · [discovery/endpoints.ts](#discoveryendpointsts) ·
6
+ [Serving the documents](#serving-the-documents) · [Announcing](#announcing) · [The switches](#the-switches) ·
7
+ [Looking for others](#looking-for-others) · [Docker](#docker) · [Testing it](#testing-it)
8
+
9
+ ## What the kit does and the libraries do
10
+
11
+ Three libraries do the work, and the kit only names things the way every cubicecho server names them:
12
+
13
+ | Package | Does |
14
+ |---|---|
15
+ | `@cubicecho/discovery-core` | Serving and fetching the documents, and the one mDNS responder a process shares. Never imported by a server |
16
+ | `@cubicecho/graphql-mdns-discovery` | The GraphQL services document and `_graphql._tcp` |
17
+ | `@cubicecho/mcp-discovery` | MCP Server Cards, the AI Catalog and `_mcp._tcp` |
18
+
19
+ | Kit export | Entry | Builds |
20
+ |---|---|---|
21
+ | `discoveryNames({ app, title })` | `/discovery` | Every name the server advertises under: `AI Router on nas`, `io.github.cubicecho.ai-router.nas/<endpoint>`, `urn:air` publisher `nas.ai-router`, the GitHub link |
22
+ | `graphqlEndpoint(names, …)` | `/discovery` | The server's entry in its GraphQL services document |
23
+ | `mcpEndpoint(names, …)` | `/mcp` | Its MCP door's AI Catalog entry and Server Card |
24
+ | `createLanAdvertiser(…)` | `/discovery` | One `sync()` and one `close()` for both announcements |
25
+
26
+ **Install** `@cubicecho/graphql-mdns-discovery` for `/discovery`, `@cubicecho/mcp-discovery` too when the server has `/mcp`, and `bonjour-service` when it announces or looks. A server without an MCP door never loads mcp-discovery: the advertiser imports it only when given an `mcpPath`. `bonjour-service` is loaded on the first announcement.
27
+
28
+ **One copy of discovery-core.** Both libraries depend on it. Its errors are `instanceof`-checked across the two, and its responder is one per copy: two copies are two responders, and stopping one sends a goodbye that takes the other's address records with it. `npm ls @cubicecho/discovery-core` shows one version, deduped.
29
+
30
+ ## discovery/endpoints.ts
31
+
32
+ ```ts
33
+ import { discoveryNames, graphqlEndpoint } from '@cubicecho/server-kit/discovery';
34
+ import { mcpEndpoint } from '@cubicecho/server-kit/mcp';
35
+ import { version } from '../core/config.ts';
36
+
37
+ /** Every name the server advertises under. Read once: the hostname doesn't change. */
38
+ export const names = discoveryNames({ app: 'ai-router', title: 'AI Router' });
39
+
40
+ /** The GraphQL API, in /.well-known/graphql-services.json. */
41
+ export const graphqlApi = graphqlEndpoint(names, {
42
+ version: version(),
43
+ auth: 'Bearer <session token, or a user key>',
44
+ });
45
+
46
+ /** The MCP door, in the AI Catalog. */
47
+ export const mcpDoor = mcpEndpoint(names, {
48
+ endpoint: 'agents',
49
+ version: version(),
50
+ description: "Agents as MCP tools: one per agent a workspace key's workspace may run.",
51
+ auth: 'Bearer <workspace key>: an air_… key from a workspace in the router',
52
+ });
53
+ ```
54
+
55
+ - **`app` is the repository's name** and `title` what people call it. Both go into names other machines keep, so neither changes once a server has shipped.
56
+ - **`endpoint` is the door's stable name**, the last part of its card name and `urn:air` id. Never a path, a port or a version.
57
+ - **What's public names no data.** The documents are served to anyone, so a description says what kind of thing the door is, never which agents or tables are behind it. `auth` says what goes in the header; the value is never in any document.
58
+ - `graphqlEndpoint`'s `fields` adds what only this server has, per request: its subscriptions (`{ url: `${origin.replace(/^http/, 'ws')}/graphql`, protocol: 'graphql-ws' }`), or a `schemaUrl`. It wins over the rest.
59
+ - A server with several MCP doors or a door per record (mcp-router) builds its catalog entries itself, with `names.serviceName(endpoint)` and `names.publisher` so they read the same.
60
+
61
+ ## Serving the documents
62
+
63
+ In `createApp`, at the root and before any auth guard or the static handler:
64
+
65
+ ```ts
66
+ import { graphqlDiscoveryMiddleware } from '@cubicecho/graphql-mdns-discovery';
67
+ import { discoveryMiddleware } from '@cubicecho/mcp-discovery';
68
+
69
+ app.use(graphqlDiscoveryMiddleware(() => [graphqlApi]));
70
+ app.use(discoveryMiddleware(() => [mcpDoor]));
71
+ ```
72
+
73
+ - **Served whether or not the server announces.** They are public and cost nothing, and a client that was given the address reads them without mDNS.
74
+ - Each answers only its own paths and passes everything else on, in either order.
75
+ - The URLs in them come from the request's `Host`, so a client on the LAN is told LAN addresses. Behind a proxy that ends TLS, the origin reads as `http`: return paths instead (the library's serving.md).
76
+
77
+ ## Announcing
78
+
79
+ In index.ts, after the app is built:
80
+
81
+ ```ts
82
+ import { createLanAdvertiser } from '@cubicecho/server-kit/discovery';
83
+ import { names } from './discovery/endpoints.ts';
84
+
85
+ const advertiser = createLanAdvertiser({
86
+ isWanted: mdnsAdvertise,
87
+ options: () => ({ name: names.instance, port: port(), mcpPath: '/mcp' }),
88
+ log: (message) => console.log(`[discovery] ${message}`),
89
+ });
90
+ const server = app.listen(port(), LISTEN_HOST, () => {
91
+ // After listen, so a watcher that finds the announcement can already read the documents.
92
+ void advertiser.sync();
93
+ });
94
+ stopOnSignals(server, {
95
+ // First, so the goodbye goes out while the server still answers.
96
+ before: () => advertiser.close(),
97
+ after: closeDatabase,
98
+ });
99
+ ```
100
+
101
+ - **`_graphql._tcp` always, `_mcp._tcp` with an `mcpPath`,** under one instance name and port. `graphqlPath` is `/graphql` unless given.
102
+ - **One that fails is logged and the server carries on.** The name taken, multicast blocked: discovery is never a reason not to serve. The next `sync()` tries again.
103
+ - **`options` is read when an announcement starts**, so a changed port takes effect on the next one.
104
+ - Listen on the LAN (`0.0.0.0`), not only localhost, or what is announced can't be reached.
105
+
106
+ ## The switches
107
+
108
+ The kit reads no environment. Whether the server announces is the server's own switch, passed as `isWanted`, wherever it keeps it: an env flag read in core/config.ts, a row in its settings table, a constant.
109
+
110
+ - **Off unless the server turns it on.** mDNS needs the host's network (Docker below), and a server that is never looked for has no reason to multicast.
111
+ - **It is read on every `sync()`.** A switch the server keeps in its database calls `advertiser.sync()` after saving it, and the announcement starts or stops without a restart.
112
+ - **Announcing and looking are two switches.** One says the server may be found, the other that it trusts the network enough to suggest what it finds.
113
+
114
+ ## Looking for others
115
+
116
+ What a server does with what it finds is its own: the kit has no part in it. Use the libraries' watchers, `watchGraphqlServices` from `@cubicecho/graphql-mdns-discovery/mdns` and `watchServers` from `@cubicecho/mcp-discovery/mdns`:
117
+
118
+ - Import them with `await import(…)` behind the server's own switch, so a server that doesn't look never loads them.
119
+ - Skip `names.instance`: a server that announces sees itself.
120
+ - **A found server is a suggestion.** Anything on the network can announce. A person adds it, or the server's own rule allows it, never the name alone.
121
+ - Stop the watch in `stopOnSignals`'s `before`, beside `advertiser.close()`.
122
+
123
+ ## Docker
124
+
125
+ Docker's default bridge network drops multicast. A container that announces or looks runs with `network_mode: host`, and the switch stays off in any compose file that doesn't.
126
+
127
+ ## Testing it
128
+
129
+ - **The documents**, in `http/app.test.ts` (testing.md): the services document lists `names.serviceName('graphql')` with the request's origin, and the card names no data and holds no secret. Read the card through the catalog's `url`.
130
+ - **The announcement**, without multicast: `createLanAdvertiser`'s `announce` takes a function per type, which a test records. Real multicast is the libraries' to test, and is skipped when `CI=true`.
package/skill/mcp.md CHANGED
@@ -65,6 +65,7 @@ export function createMcpHandler(schema: GraphQLSchema, contextFor: ContextFacto
65
65
  - **`app.all`, not `app.post`:** clients also send GET and DELETE to the same path, and with `post` those get an Express HTML 404.
66
66
  - The same body cap as `/graphql`, never a bare `express.json()`. On plain `node:http`, parse the body yourself with the same cap.
67
67
  - Close it (`await handler.close()`) in `stopOnSignals`'s `after`, before the pool.
68
+ - Its AI Catalog entry and Server Card are `mcpEndpoint(names, …)`, served beside the GraphQL services document (discovery.md).
68
69
 
69
70
  ## Limits on this door
70
71