@apso/cli 0.50.1 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -134,6 +134,26 @@ curl -i -H "x-api-key: $APSO_API_KEY" -H "Prefer: count=exact" "http://localhost
134
134
 
135
135
  The full list of what is supported and what is refused is in the `@apso/crud` package, in `docs/DIALECTS.md`. Python and Go services accept this syntax and, for now, the nestjsx syntax as well.
136
136
 
137
+ ## MCP tools on a generated API
138
+
139
+ Add `mcp` to an entity in `.apsorc` and its routes are served as MCP tools. `"mcp": true` exposes read, create, update and delete. A list such as `["read"]` exposes only those.
140
+
141
+ A service has two MCP addresses, in TypeScript, Python and Go:
142
+
143
+ | Address | Who it is for | Credential |
144
+ |---------|---------------|------------|
145
+ | `/mcp/internal` | Your team, agents and scripts | The service's API key in `x-api-key` |
146
+ | `/mcp` | Your app's end users | A token from the sign-in provider in the `auth` block |
147
+
148
+ - `/mcp/internal` exists whenever an entity has `mcp`. It does not need an `auth` block. A caller there is a service caller: every tool, no tenant scope.
149
+ - `/mcp` exists only when `.apsorc` has an `auth` block. A caller there is the signed-in user, under the same scope and permission rules as REST. An API key is not accepted there.
150
+
151
+ ```bash
152
+ claude mcp add --transport http my-api http://localhost:3000/mcp/internal --header "x-api-key: $APSO_API_KEY"
153
+ ```
154
+
155
+ Set `MCP_RESOURCE_URL` to the public URL of `/mcp` when the service runs behind a proxy. Details are in [docs/access-rules.md](docs/access-rules.md#mcp-addresses).
156
+
137
157
  ## Commands
138
158
 
139
159
  | Command | Subcommands | Description |
@@ -20,7 +20,7 @@ class Generate extends base_command_1.default {
20
20
  const { flags } = await this.parse(Generate);
21
21
  const skipFormat = flags["skip-format"];
22
22
  const totalBuildStart = perf_hooks_1.performance.now();
23
- const { rootFolder, entities, relationshipMap, apiType, auth, emitEvents, http, coAuthor, language: configLanguage } = (0, lib_1.parseApsorc)();
23
+ const { rootFolder, entities, relationshipMap, apiType, auth, emitEvents, http, coAuthor, query, guards, language: configLanguage } = (0, lib_1.parseApsorc)();
24
24
  // Resolve language: flag > .apsorc > prompt
25
25
  let language;
26
26
  if (flags.language) {
@@ -180,6 +180,7 @@ class Generate extends base_command_1.default {
180
180
  apiType: lowerCaseApiType,
181
181
  relationshipMap,
182
182
  auth,
183
+ query,
183
184
  }));
184
185
  }
185
186
  // eslint-disable-next-line no-await-in-loop
@@ -209,7 +210,7 @@ class Generate extends base_command_1.default {
209
210
  await writeGenerated(file.path, file.content);
210
211
  }
211
212
  // Generate index module
212
- const indexFiles = await generator.generateIndexModule(entities, lowerCaseApiType, { emitEvents, http, auth });
213
+ const indexFiles = await generator.generateIndexModule(entities, lowerCaseApiType, { emitEvents, http, auth, guards });
213
214
  for (const file of indexFiles) {
214
215
  // eslint-disable-next-line no-await-in-loop
215
216
  await writeGenerated(file.path, file.content);
@@ -278,7 +279,7 @@ class Generate extends base_command_1.default {
278
279
  if (language === "typescript" && entities.some((entity) => entity.mcp)) {
279
280
  const wired = (0, crud_deps_1.ensureMcpWiring)(process.cwd(), rootFolder);
280
281
  if (wired.length > 0)
281
- console.log(`[apso] Set up MCP tools at /mcp (updated ${wired.join(", ")}). Run npm install before building.`);
282
+ console.log(`[apso] Set up MCP tools at /mcp/internal for API keys, and at /mcp for signed-in users when .apsorc has an auth block (updated ${wired.join(", ")}). Run npm install before building.`);
282
283
  }
283
284
  if ((language === "python" || language === "go") &&
284
285
  !entities.some((entity) => entity.mcp)) {
@@ -290,7 +291,7 @@ class Generate extends base_command_1.default {
290
291
  entities.some((entity) => entity.mcp)) {
291
292
  const wired = (0, crud_deps_1.ensureAppMcpWiring)(process.cwd(), language);
292
293
  if (wired.length > 0)
293
- console.log(`[apso] Set up MCP tools at /mcp (updated ${wired.join(", ")}). ${language === "python"
294
+ console.log(`[apso] Set up MCP tools at /mcp/internal for API keys, and at /mcp for signed-in users when .apsorc has an auth block (updated ${wired.join(", ")}). ${language === "python"
294
295
  ? "Reinstall the project's dependencies."
295
296
  : "Run go mod tidy before building; the MCP SDK needs Go 1.25."}`);
296
297
  }
@@ -280,7 +280,7 @@ class McpServe extends base_command_1.default {
280
280
  isError: true,
281
281
  };
282
282
  }
283
- const { rootFolder, entities, relationshipMap, apiType, auth, language: configLanguage, } = (0, apsorc_parser_1.parseApsorc)();
283
+ const { rootFolder, entities, relationshipMap, apiType, auth, query, guards, language: configLanguage, } = (0, apsorc_parser_1.parseApsorc)();
284
284
  // Resolve language
285
285
  let lang;
286
286
  if (language) {
@@ -371,6 +371,7 @@ class McpServe extends base_command_1.default {
371
371
  apiType: lowerCaseApiType,
372
372
  relationshipMap,
373
373
  auth,
374
+ query,
374
375
  }),
375
376
  generator.generateModule({
376
377
  entity,
@@ -401,7 +402,7 @@ class McpServe extends base_command_1.default {
401
402
  if (guardFiles.length > 0)
402
403
  (0, crud_deps_1.writeAccessManifest)(process.cwd(), this.config.version);
403
404
  // Generate index module
404
- const indexFiles = await generator.generateIndexModule(entities, lowerCaseApiType, { auth });
405
+ const indexFiles = await generator.generateIndexModule(entities, lowerCaseApiType, { auth, guards });
405
406
  for (const file of indexFiles) {
406
407
  const fullPath = path.join(autogenPath, file.path);
407
408
  // eslint-disable-next-line no-await-in-loop
@@ -160,7 +160,7 @@
160
160
  {
161
161
  "id": "R22",
162
162
  "group": "MCP",
163
- "rule": "When sign-in is configured, every MCP request needs a valid token issued for the MCP endpoint, including listing tools.",
163
+ "rule": "When sign-in is configured, every request to the external MCP address (`/mcp`) needs a valid token issued for it, including listing tools.",
164
164
  "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
165
165
  },
166
166
  {
@@ -194,7 +194,7 @@
194
194
  {
195
195
  "id": "R27",
196
196
  "group": "Build time",
197
- "rule": "A schema that cannot be enforced fails at generate: MCP or permissions without sign-in, an unprotected grants entity. A tenant scope whose provider maps no tenant claim does not fail: generate warns, and at run time a token with no tenant gets the \"no tenant\" 403 on tenant-scoped entities, in every language.",
197
+ "rule": "A schema that cannot be enforced fails at generate: permissions without sign-in, an unprotected grants entity. A tenant scope whose provider maps no tenant claim does not fail: generate warns, and at run time a token with no tenant gets the \"no tenant\" 403 on tenant-scoped entities, in every language.",
198
198
  "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
199
199
  },
200
200
  {
@@ -202,6 +202,13 @@
202
202
  "group": "Service callers",
203
203
  "rule": "The auth entities answer a service caller only. With the `better-auth` provider these are the session, user and membership entities named in the `auth` block, plus Better Auth's other tables. A signed-in user is refused on every one of their routes, no other entity's route loads them through a join or an embed, and `apso generate` refuses `mcp` on them.",
204
204
  "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" }
205
+ },
206
+ {
207
+ "id": "R29",
208
+ "group": "MCP",
209
+ "rule": "MCP tools have one address per audience. `/mcp/internal` exists whenever an entity has `mcp`, with or without sign-in, and answers service callers only: an API key, or the gateway's service token for a key or an Apso user. A user token is not a credential there. `/mcp` exists only when sign-in is configured and answers signed-in users only: an API key or a service token is not a credential there and does not reach the route a tool calls.",
210
+ "status": { "typescript": "enforced", "python": "enforced", "go": "enforced" },
211
+ "issue": "apsoai/cli#232"
205
212
  }
206
213
  ]
207
214
  }
@@ -1,7 +1,7 @@
1
1
  import { Entity } from "./types/entity";
2
2
  import { ApsorcRelationship, Relationship, RelationshipMap } from "./types/relationship";
3
3
  import { AuthConfig } from "./types/auth";
4
- import { TargetLanguage } from "./types/generator";
4
+ import { QueryConfig, TargetLanguage } from "./types/generator";
5
5
  export declare enum ApiType {
6
6
  Graphql = "graphql",
7
7
  Rest = "rest"
@@ -31,6 +31,14 @@ export type ApsorcType = {
31
31
  * trailer. Defaults to enabled.
32
32
  */
33
33
  coAuthor?: boolean;
34
+ /** TypeScript list route settings; see QueryConfig. */
35
+ query?: QueryConfig;
36
+ /**
37
+ * TypeScript only. False leaves the generated GuardsModule out of the
38
+ * autogen module list, for an app that registers its own global guards.
39
+ * Not allowed with `auth`, whose checks run in those guards.
40
+ */
41
+ guards?: boolean;
34
42
  };
35
43
  type ParsedApsorcData = {
36
44
  entities: Entity[];
@@ -49,6 +57,8 @@ export type ParsedApsorc = {
49
57
  http?: boolean;
50
58
  /** Opt-out for the Apso commit co-author hook (defaults to enabled). */
51
59
  coAuthor?: boolean;
60
+ query?: QueryConfig;
61
+ guards?: boolean;
52
62
  };
53
63
  export declare const parseApsorcV1: (apsorc: ApsorcType) => ParsedApsorcData;
54
64
  /**
@@ -94,6 +104,8 @@ export declare const dedupeIndexes: (entity: Entity) => Entity;
94
104
  */
95
105
  export declare const dedupeOneToOneUniques: (entity: Entity, relationships?: Relationship[]) => Entity;
96
106
  export declare const parseApsorcV2: (apsorc: ApsorcType) => ParsedApsorcData;
107
+ /** Checks the .apsorc `query` block; undefined when it is left out. */
108
+ export declare function parseQuery(raw: unknown): QueryConfig | undefined;
97
109
  export declare const parseApsorc: () => ParsedApsorc;
98
110
  /**
99
111
  * Finds the .apsorc configuration file path.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.findConfigPath = exports.readApsorcFile = exports.parseApsorc = exports.parseApsorcV2 = exports.dedupeOneToOneUniques = exports.dedupeIndexes = exports.assertCodegenSafeNames = exports.ApsorcNamingError = exports.parseApsorcV1 = exports.ApiType = void 0;
3
+ exports.findConfigPath = exports.readApsorcFile = exports.parseApsorc = exports.parseQuery = exports.parseApsorcV2 = exports.dedupeOneToOneUniques = exports.dedupeIndexes = exports.assertCodegenSafeNames = exports.ApsorcNamingError = exports.parseApsorcV1 = exports.ApiType = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const fs = tslib_1.__importStar(require("fs"));
6
6
  const path = tslib_1.__importStar(require("path"));
@@ -136,6 +136,12 @@ const parseRc = () => {
136
136
  const emitEvents = apsoConfig.emitEvents;
137
137
  const http = apsoConfig.http;
138
138
  const coAuthor = apsoConfig.coAuthor;
139
+ const query = parseQuery(apsoConfig.query);
140
+ const guards = apsoConfig.guards;
141
+ if (guards !== undefined && typeof guards !== "boolean")
142
+ throw new Error(`.apsorc "guards" must be true or false`);
143
+ if (guards === false && auth)
144
+ throw new Error(`.apsorc "guards": false leaves out the guards that enforce "auth"; remove one of them`);
139
145
  return {
140
146
  rootFolder,
141
147
  apiType,
@@ -147,8 +153,37 @@ const parseRc = () => {
147
153
  emitEvents,
148
154
  http,
149
155
  coAuthor,
156
+ query,
157
+ guards,
150
158
  };
151
159
  };
160
+ const DIALECTS = new Set(["postgrest", "nestjsx"]);
161
+ /** Checks the .apsorc `query` block; undefined when it is left out. */
162
+ function parseQuery(raw) {
163
+ if (raw === undefined)
164
+ return undefined;
165
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
166
+ throw new Error(`.apsorc "query" must be an object`);
167
+ const { dialects, limit, alwaysPaginate, ...rest } = raw;
168
+ const unknown = Object.keys(rest);
169
+ if (unknown.length > 0)
170
+ throw new Error(`.apsorc "query" has unknown setting(s) ${unknown.join(", ")}; use dialects, limit or alwaysPaginate`);
171
+ if (dialects !== undefined &&
172
+ (!Array.isArray(dialects) ||
173
+ dialects.length === 0 ||
174
+ dialects.some((d) => !DIALECTS.has(d))))
175
+ throw new Error(`.apsorc "query.dialects" must list one or both of "postgrest" and "nestjsx"`);
176
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > 100))
177
+ throw new Error(`.apsorc "query.limit" must be a whole number from 1 to 100`);
178
+ if (alwaysPaginate !== undefined && typeof alwaysPaginate !== "boolean")
179
+ throw new Error(`.apsorc "query.alwaysPaginate" must be true or false`);
180
+ return {
181
+ dialects: dialects,
182
+ limit: limit,
183
+ alwaysPaginate: alwaysPaginate,
184
+ };
185
+ }
186
+ exports.parseQuery = parseQuery;
152
187
  const parseApsorc = () => {
153
188
  const debug = process.env.DEBUG;
154
189
  const start = perf_hooks_1.performance.now();
@@ -169,6 +204,8 @@ const parseApsorc = () => {
169
204
  emitEvents: apsoConfig.emitEvents,
170
205
  http: apsoConfig.http,
171
206
  coAuthor: apsoConfig.coAuthor,
207
+ query: apsoConfig.query,
208
+ guards: apsoConfig.guards,
172
209
  ...(0, exports.parseApsorcV1)(apsoConfig),
173
210
  };
174
211
  if (debug) {
@@ -188,6 +225,8 @@ const parseApsorc = () => {
188
225
  emitEvents: apsoConfig.emitEvents,
189
226
  http: apsoConfig.http,
190
227
  coAuthor: apsoConfig.coAuthor,
228
+ query: apsoConfig.query,
229
+ guards: apsoConfig.guards,
191
230
  ...(() => {
192
231
  const relStart = perf_hooks_1.performance.now();
193
232
  const parsed = (0, exports.parseApsorcV2)(apsoConfig);
@@ -703,7 +703,9 @@ ${modelRefs}
703
703
  }),
704
704
  });
705
705
  }
706
- // The /mcp endpoint; cmd/main.go mounts it (see ensureGoMcpWiring).
706
+ // The MCP addresses; cmd/main.go mounts them (see ensureGoMcpWiring).
707
+ // The external one, /mcp, is served when there is an issuer to sign in
708
+ // with; /mcp/internal takes the API key.
707
709
  if (tools.length > 0)
708
710
  files.push({
709
711
  path: "routes/mcp.go",
@@ -579,9 +579,13 @@ ${downStatements || " pass"}
579
579
  path: "permissions.py",
580
580
  content: await this.renderTemplate("./permissions", { permissions }),
581
581
  });
582
- // The /mcp endpoint; app/main.py mounts it (see ensurePythonMcpWiring).
582
+ // The MCP addresses; app/main.py mounts them (see ensurePythonMcpWiring).
583
+ // The external one, /mcp, needs sign-in; /mcp/internal takes the API key.
583
584
  if (mcp)
584
- files.push({ path: "mcp.py", content: await this.renderTemplate("./mcp", {}) });
585
+ files.push({
586
+ path: "mcp.py",
587
+ content: await this.renderTemplate("./mcp", { external: Boolean(data.jwt) }),
588
+ });
585
589
  return files;
586
590
  }
587
591
  async generateQueryUtils(_entities, _apiType) {
@@ -16,9 +16,10 @@ export declare class TypeScriptGenerator extends BaseGenerator {
16
16
  generateModule(options: EntityGenerationOptions): Promise<GeneratedFile[]>;
17
17
  generateMigration(_options: MigrationGenerationOptions): Promise<GeneratedFile[]>;
18
18
  generateEnums(entities: Entity[], apiType: string): Promise<GeneratedFile[]>;
19
- generateIndexModule(entities: Entity[], apiType: string, _opts?: {
19
+ generateIndexModule(entities: Entity[], apiType: string, opts?: {
20
20
  emitEvents?: boolean;
21
21
  auth?: AuthConfig;
22
+ guards?: boolean;
22
23
  }): Promise<GeneratedFile[]>;
23
24
  generateGuards(entities: Entity[], auth?: AuthConfig, relationshipMap?: RelationshipMap): Promise<GeneratedFile[]>;
24
25
  /**
@@ -125,7 +125,7 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
125
125
  ];
126
126
  }
127
127
  async generateController(options) {
128
- var _a;
128
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
129
129
  const { entity, relationships, relationshipMap, auth } = options;
130
130
  const { name: entityName } = entity;
131
131
  // Auth entities are for service callers only, so no other entity's
@@ -162,8 +162,6 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
162
162
  bypassRoles: scoped.bypassRoles,
163
163
  };
164
164
  const mcp = (0, guards_1.mcpOperations)(entity);
165
- if (mcp.length > 0 && !auth)
166
- throw new Error(`${entityName}.mcp needs an auth block in .apsorc: MCP tools act as the signed-in caller`);
167
165
  const data = {
168
166
  svcName,
169
167
  ctrlName,
@@ -185,6 +183,10 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
185
183
  mcp,
186
184
  mcpName: (0, casing_1.snakeCase)(entityName),
187
185
  mcpPluralName: (0, casing_1.snakeCase)(pluralEntityName),
186
+ dialects: (_c = (_b = options.query) === null || _b === void 0 ? void 0 : _b.dialects) !== null && _c !== void 0 ? _c : ["postgrest"],
187
+ dialectList: ((_e = (_d = options.query) === null || _d === void 0 ? void 0 : _d.dialects) !== null && _e !== void 0 ? _e : ["postgrest"]).map((d) => `'${d}'`).join(", "),
188
+ limit: (_g = (_f = options.query) === null || _f === void 0 ? void 0 : _f.limit) !== null && _g !== void 0 ? _g : 25,
189
+ alwaysPaginate: (_j = (_h = options.query) === null || _h === void 0 ? void 0 : _h.alwaysPaginate) !== null && _j !== void 0 ? _j : false,
188
190
  };
189
191
  const controllerContent = await this.renderTemplate("./rest/controller-rest", data);
190
192
  const specContent = await this.renderTemplate("./rest/controller-rest-spec", data);
@@ -357,10 +359,10 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
357
359
  },
358
360
  ];
359
361
  }
360
- async generateIndexModule(entities, apiType, _opts) {
362
+ async generateIndexModule(entities, apiType, opts) {
361
363
  // Listing GuardsModule is what turns the global guards on; every service
362
- // has at least the API key check.
363
- const content = await this.renderTemplate(`./${apiType}/index-module-${apiType}`, { entities });
364
+ // has at least the API key check. `.apsorc` "guards": false leaves it out.
365
+ const content = await this.renderTemplate(`./${apiType}/index-module-${apiType}`, { entities, guards: (opts === null || opts === void 0 ? void 0 : opts.guards) !== false });
364
366
  return [
365
367
  {
366
368
  path: "index.ts",
@@ -382,6 +384,7 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
382
384
  }
383
385
  const scopedEntities = (0, guards_1.getScopedEntities)(entities, relationshipMap);
384
386
  const files = [];
387
+ const mcp = entities.some((e) => (0, guards_1.mcpOperations)(e).length > 0);
385
388
  const templateData = {
386
389
  scopedEntities,
387
390
  // Every entity by route: the scope guard checks relations in write bodies.
@@ -394,8 +397,10 @@ class TypeScriptGenerator extends base_1.BaseGenerator {
394
397
  authRoutes: (0, guards_1.authEntityRoutes)(entities, auth),
395
398
  jwt,
396
399
  permissions,
397
- // OAuth sign-in for MCP clients: tokens come from the listed issuers.
398
- mcpAuth: hasAuth && entities.some((e) => (0, guards_1.mcpOperations)(e).length > 0),
400
+ // MCP tools are served at /mcp/internal for service callers, and at /mcp
401
+ // for signed-in users when there is sign-in: tokens come from the listed issuers.
402
+ mcp,
403
+ mcpAuth: hasAuth && mcp,
399
404
  };
400
405
  // The API key check is part of every service.
401
406
  files.push({
@@ -66,8 +66,10 @@ export declare const authEntityRoutes: (entities: Entity[], auth?: AuthConfig) =
66
66
  /**
67
67
  * An entity's MCP operations and the names its tools get, the same in every
68
68
  * language: list_line_items, get_line_item, create_line_item and so on.
69
+ * `mcp` does not need an auth block: without one the tools are served to
70
+ * service callers only. The second argument is no longer read.
69
71
  */
70
- export declare function mcpToolNames(entity: Entity, auth?: AuthConfig): {
72
+ export declare function mcpToolNames(entity: Entity, _auth?: AuthConfig): {
71
73
  mcp: ("create" | "update" | "delete" | "read")[];
72
74
  mcpName: string;
73
75
  mcpPluralName: string;
@@ -183,13 +183,12 @@ exports.authEntityRoutes = authEntityRoutes;
183
183
  /**
184
184
  * An entity's MCP operations and the names its tools get, the same in every
185
185
  * language: list_line_items, get_line_item, create_line_item and so on.
186
+ * `mcp` does not need an auth block: without one the tools are served to
187
+ * service callers only. The second argument is no longer read.
186
188
  */
187
- function mcpToolNames(entity, auth) {
188
- const mcp = mcpOperations(entity);
189
- if (mcp.length > 0 && !auth)
190
- throw new Error(`${entity.name}.mcp needs an auth block in .apsorc: MCP tools act as the signed-in caller`);
189
+ function mcpToolNames(entity, _auth) {
191
190
  return {
192
- mcp,
191
+ mcp: mcpOperations(entity),
193
192
  mcpName: (0, casing_1.snakeCase)(entity.name),
194
193
  mcpPluralName: (0, casing_1.snakeCase)((0, pluralize_1.default)(entity.name)),
195
194
  };
@@ -2,8 +2,21 @@
2
2
 
3
3
  package routes
4
4
 
5
- // MCP tools at /mcp (Streamable HTTP, stateless), served with the official MCP
6
- // SDK for Go.
5
+ // MCP tools (Streamable HTTP, stateless), served with the official MCP SDK for
6
+ // Go at two addresses, one per audience:
7
+ //
8
+ <% if (it.issuers.length > 0) { %>
9
+ // - /mcp, the external address, for your end users. It takes a signed-in
10
+ // user's token in Authorization: Bearer and nothing else: an API key is
11
+ // not read here.
12
+ <% } else { %>
13
+ // - /mcp, the external address, for your end users, is not served: .apsorc
14
+ // has no auth block to sign them in with.
15
+ <% } %>
16
+ // - /mcp/internal, for your own team, agents and scripts. It takes the
17
+ // service's API key (the same key source as the REST routes) and nothing
18
+ // else: the Authorization header is not read here. The caller is a
19
+ // service caller.
7
20
  //
8
21
  // A tool is a route. When an agent calls a tool, the request is sent through
9
22
  // the Gin engine in memory with the caller's headers, so authentication,
@@ -14,10 +27,18 @@ package routes
14
27
  // written here from .apsorc: path and query parameters are top-level
15
28
  // arguments, the JSON body is the "body" argument.
16
29
  //
17
- // Every request to /mcp passes the service's own auth check first. A request
18
- // with no valid credential gets the 401 that starts OAuth sign-in in an MCP
19
- // client, and /.well-known/oauth-protected-resource names the identity
20
- // provider (RFC 9728).
30
+ // Every request passes the service's own auth check first, on the credential
31
+ // its address reads. A request with no valid credential gets a 401.
32
+ <% if (it.issuers.length > 0) { %>
33
+ // On /mcp that 401 starts OAuth sign-in in an MCP client, and
34
+ // /.well-known/oauth-protected-resource names the identity provider (RFC 9728).
35
+ <% } %>
36
+ //
37
+ // When APSO_INTERNAL_AUTH_ISSUER is set (the platform sets it), the 401 on
38
+ // /mcp/internal starts an Apso sign-in the same way, and
39
+ // /.well-known/oauth-protected-resource/mcp/internal names that issuer. The
40
+ // platform's gateway turns the Apso token into the service token this service
41
+ // checks.
21
42
  //
22
43
  // Serve your own route as a tool by calling RegisterMCPTool before MountMCP.
23
44
 
@@ -87,8 +108,9 @@ func RegisterMCPTool(t MCPTool) {
87
108
  }
88
109
 
89
110
  const (
90
- mcpPath = "/mcp"
91
- prmPath = "/.well-known/oauth-protected-resource"
111
+ mcpPath = "/mcp"
112
+ mcpInternal = "/internal"
113
+ prmPath = "/.well-known/oauth-protected-resource"
92
114
  )
93
115
 
94
116
  // Headers that describe the MCP request itself, not the caller. Everything
@@ -103,6 +125,7 @@ var mcpNotForwarded = map[string]bool{
103
125
  "transfer-encoding": true,
104
126
  }
105
127
 
128
+ <% if (it.issuers.length > 0) { %>
106
129
  func mcpEnv(name, fallback string) string {
107
130
  if v := os.Getenv(name); v != "" {
108
131
  return v
@@ -116,16 +139,18 @@ var mcpIssuers = []string{
116
139
  mcpEnv(<%~ JSON.stringify(p.env) %>, <%~ JSON.stringify(p.issuer) %>),
117
140
  <% }) %>
118
141
  }
142
+ <% } %>
119
143
 
120
144
  func mcpFirst(v string) string {
121
145
  return strings.TrimSpace(strings.Split(v, ",")[0])
122
146
  }
123
147
 
124
- // mcpResourceURL is the MCP endpoint's public URL: MCP_RESOURCE_URL, else
125
- // what the request used.
126
- func mcpResourceURL(c *gin.Context) string {
148
+ // mcpResourceURL is an MCP address's public URL: from MCP_RESOURCE_URL (the
149
+ // external address; the internal one is that + /internal), else from what the
150
+ // request used. suffix is "" or mcpInternal.
151
+ func mcpResourceURL(c *gin.Context, suffix string) string {
127
152
  if v := os.Getenv("MCP_RESOURCE_URL"); v != "" {
128
- return strings.TrimRight(v, "/")
153
+ return strings.TrimRight(v, "/") + suffix
129
154
  }
130
155
  proto := mcpFirst(c.GetHeader("X-Forwarded-Proto"))
131
156
  if proto == "" {
@@ -138,13 +163,20 @@ func mcpResourceURL(c *gin.Context) string {
138
163
  if host == "" {
139
164
  host = c.Request.Host
140
165
  }
141
- return proto + "://" + host + mcpPath
166
+ return proto + "://" + host + mcpPath + suffix
167
+ }
168
+
169
+ // mcpMetadata is an address's protected resource metadata (RFC 9728).
170
+ type mcpMetadata struct {
171
+ Resource string `json:"resource"`
172
+ AuthorizationServers []string `json:"authorization_servers"`
173
+ BearerMethodsSupported []string `json:"bearer_methods_supported"`
142
174
  }
143
175
 
144
- func mcpMetadataURL(c *gin.Context) string {
145
- u, err := url.Parse(mcpResourceURL(c))
176
+ func mcpMetadataURL(c *gin.Context, suffix string) string {
177
+ u, err := url.Parse(mcpResourceURL(c, suffix))
146
178
  if err != nil {
147
- return prmPath + mcpPath
179
+ return prmPath + mcpPath + suffix
148
180
  }
149
181
  return u.Scheme + "://" + u.Host + prmPath + u.Path
150
182
  }
@@ -240,8 +272,8 @@ func mcpCall(ctx context.Context, engine http.Handler, base string, t MCPTool, r
240
272
  return mcpText(text, rec.Code >= 400)
241
273
  }
242
274
 
243
- // MountMCP serves the tools at POST /mcp on the engine. api is the group the
244
- // routes are registered on. Call it after RegisterAllRoutes.
275
+ // MountMCP serves the tools on the engine. api is the group the routes are
276
+ // registered on. Call it after RegisterAllRoutes.
245
277
  func MountMCP(r *gin.Engine, api *gin.RouterGroup) {
246
278
  server := mcp.NewServer(&mcp.Implementation{Name: "api", Version: "1.0"}, nil)
247
279
  seen := map[string]bool{}
@@ -266,42 +298,60 @@ func MountMCP(r *gin.Engine, api *gin.RouterGroup) {
266
298
  &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true},
267
299
  )
268
300
 
269
- r.Any(mcpPath,
270
- func(c *gin.Context) {
271
- if c.Request.Method != http.MethodPost {
272
- c.Header("Allow", http.MethodPost)
273
- c.AbortWithStatus(http.StatusMethodNotAllowed)
274
- return
275
- }
276
- // The 401 is what starts sign-in: it points the client at the
277
- // metadata. Set before the auth check answers, cleared once it passes.
278
- if c.GetHeader("x-api-key") == "" && c.GetHeader("x-apso-service-token") == "" {
279
- challenge := `Bearer resource_metadata="` + mcpMetadataURL(c) + `"`
280
- if c.GetHeader("Authorization") != "" {
281
- challenge += `, error="invalid_token"`
301
+ // serve mounts one address: /mcp (suffix "") or /mcp/internal. ignored is
302
+ // the credential it does not read: a user's token on the internal one, a
303
+ // key on the external one. It is dropped before the auth check, so a
304
+ // tool's route never sees it either.
305
+ serve := func(suffix string, challenge bool, ignored ...string) {
306
+ r.Any(mcpPath+suffix,
307
+ func(c *gin.Context) {
308
+ if c.Request.Method != http.MethodPost {
309
+ c.Header("Allow", http.MethodPost)
310
+ c.AbortWithStatus(http.StatusMethodNotAllowed)
311
+ return
282
312
  }
283
- c.Header("WWW-Authenticate", challenge)
284
- }
285
- },
286
- // The same check every /api route runs: API key, then the user's token.
287
- middleware.AuthMiddleware(nil),
288
- func(c *gin.Context) {
289
- c.Writer.Header().Del("WWW-Authenticate")
290
- handler.ServeHTTP(c.Writer, c.Request)
291
- },
292
- )
313
+ sentToken := c.GetHeader("Authorization") != ""
314
+ for _, name := range ignored {
315
+ c.Request.Header.Del(name)
316
+ }
317
+ // The 401 is what starts sign-in: it points the client at the
318
+ // metadata. Set before the auth check answers, cleared once it passes.
319
+ if challenge {
320
+ value := `Bearer resource_metadata="` + mcpMetadataURL(c, suffix) + `"`
321
+ if sentToken {
322
+ value += `, error="invalid_token"`
323
+ }
324
+ c.Header("WWW-Authenticate", value)
325
+ }
326
+ },
327
+ // The same check every /api route runs, on what is left: only a key
328
+ // can pass on the internal address, only a user's token on the external one.
329
+ middleware.AuthMiddleware(nil),
330
+ func(c *gin.Context) {
331
+ c.Writer.Header().Del("WWW-Authenticate")
332
+ handler.ServeHTTP(c.Writer, c.Request)
333
+ },
334
+ )
335
+ }
336
+ // metadata tells an MCP client where to sign in. Public by design, and
337
+ // readable from a browser-based client on another origin.
338
+ metadata := func(suffix string, issuers []string) gin.HandlerFunc {
339
+ return func(c *gin.Context) {
340
+ c.Header("Access-Control-Allow-Origin", "*")
341
+ c.Header("Cache-Control", "max-age=300")
342
+ c.JSON(http.StatusOK, mcpMetadata{mcpResourceURL(c, suffix), issuers, []string{"header"}})
343
+ }
344
+ }
293
345
 
294
- // Tells an MCP client where to sign in. Public by design, and readable
295
- // from a browser-based client on another origin.
296
- metadata := func(c *gin.Context) {
297
- c.Header("Access-Control-Allow-Origin", "*")
298
- c.Header("Cache-Control", "max-age=300")
299
- c.JSON(http.StatusOK, gin.H{
300
- "resource": mcpResourceURL(c),
301
- "authorization_servers": mcpIssuers,
302
- "bearer_methods_supported": []string{"header"},
303
- })
346
+ // Where an MCP client signs in to Apso for the internal address.
347
+ internalIssuer := os.Getenv("APSO_INTERNAL_AUTH_ISSUER")
348
+ serve(mcpInternal, internalIssuer != "", "Authorization")
349
+ if internalIssuer != "" {
350
+ r.GET(prmPath+mcpPath+mcpInternal, metadata(mcpInternal, []string{internalIssuer}))
304
351
  }
305
- r.GET(prmPath, metadata)
306
- r.GET(prmPath+mcpPath, metadata)
352
+ <% if (it.issuers.length > 0) { %>
353
+ serve("", true, "x-api-key", "x-apso-service-token")
354
+ r.GET(prmPath, metadata("", mcpIssuers))
355
+ r.GET(prmPath+mcpPath, metadata("", mcpIssuers))
356
+ <% } %>
307
357
  }
@@ -198,8 +198,10 @@ func chooseKeySource() *keySource {
198
198
  return s
199
199
  }
200
200
 
201
- // keyID returns the key id from the gateway's token (sub "apikey:<id>"), or ""
202
- // when the token is not valid for this service.
201
+ // keyID returns the caller from the gateway's token: the key id of sub
202
+ // "apikey:<id>", or sub "user:<id>" as it is, an Apso sign-in the gateway
203
+ // checked (it sends one for /mcp/internal only). It is "" when the token is
204
+ // not valid for this service.
203
205
  func (s *keySource) keyID(token string) string {
204
206
  if token == "" || s.issuer == "" || s.serviceID == "" {
205
207
  return ""
@@ -218,6 +220,9 @@ func (s *keySource) keyID(token string) string {
218
220
  if err != nil || !parsed.Valid {
219
221
  return ""
220
222
  }
223
+ if user, ok := strings.CutPrefix(claims.Subject, "user:"); ok && user != "" {
224
+ return claims.Subject
225
+ }
221
226
  id, _ := strings.CutPrefix(claims.Subject, "apikey:")
222
227
  if id == claims.Subject {
223
228
  return ""