-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhttp-dispatcher.ts
More file actions
4671 lines (4340 loc) · 242 KB
/
Copy pathhttp-dispatcher.ts
File metadata and controls
4671 lines (4340 loc) · 242 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import {
ObjectKernel, getEnv, resolveLocale, evaluateAuthGate, isAuthGateAllowlisted,
shouldDenyAnonymous, ANONYMOUS_DENY_STATUS, ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_MESSAGE,
} from '@objectstack/core';
import { isMcpServerEnabled } from '@objectstack/types';
import { measureServerTiming, allowPerfDisclosure, isPerfDisclosurePrincipal } from '@objectstack/observability';
import { CoreServiceName } from '@objectstack/spec/system';
import { readServiceSelfInfo } from '@objectstack/spec/api';
import { MCP_OAUTH_SCOPES } from '@objectstack/spec/ai';
import { pluralToSingular, PLURAL_TO_SINGULAR } from '@objectstack/spec/shared';
import type { ExecutionContext } from '@objectstack/spec/kernel';
import { setPackageDisabled } from './package-state-store.js';
import { checkApiExposure } from './api-exposure.js';
/** Minimal local interface — full EnvironmentScopeManager was removed in Phase R. */
interface EnvironmentScopeManager {
touch(environmentId: string): void;
}
import {
resolveExecutionContext,
isPermissionDeniedError,
} from './security/resolve-execution-context.js';
import { generateApiKey } from './security/api-key.js';
/** Browser-safe UUID generator — prefers Web Crypto, falls back to RFC 4122 v4 */
function randomUUID(): string {
if (globalThis.crypto && typeof globalThis.crypto.randomUUID === 'function') {
return globalThis.crypto.randomUUID();
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
/** A `sys_`-prefixed object is a system table — off-limits to external MCP agents. */
function isSystemObjectName(name: string): boolean {
return /^sys_/i.test(name);
}
// The per-request `Server-Timing` disclosure predicate (#2408) now lives in
// `@objectstack/observability` — the ONE definition shared by every HTTP entry
// point that resolves a principal (this dispatcher, the REST server, the
// standalone Hono CRUD surface), so an admin-serving path can never drift into
// under- or over-disclosing (#3361). Re-exported here for back-compat with the
// dispatcher's existing consumers/tests.
export { isPerfDisclosurePrincipal } from '@objectstack/observability';
export interface HttpProtocolContext {
request: any;
response?: any;
environmentId?: string; // Resolved environment ID (set by the host's KernelResolver)
dataDriver?: any; // IDataDriver - Resolved environment-scoped driver (set by the host's KernelResolver)
/**
* Dispatcher-provided hint for the host's {@link KernelResolver}: the
* cleaned route path (API prefix stripped). Lets the resolver apply its
* own path policy (e.g. skip env resolution for control-plane routes)
* without re-deriving the dispatcher's URL handling.
*/
routePath?: string;
/**
* Dispatcher-provided hint for the host's {@link KernelResolver}: the
* UNVALIDATED environment-id candidate parsed from the scoped URL form
* (`/environments/:id/...`) or the router's `params.environmentId`.
* URL parsing is the dispatcher's routing convention, so it stays here;
* validation (registry lookup) is the resolver's job.
*/
urlEnvironmentId?: string;
/**
* Identity envelope resolved by `resolveExecutionContext` and threaded
* into every ObjectQL call so the SecurityPlugin middleware can apply
* RBAC/RLS/FLS. Optional — anonymous requests carry an empty context.
*/
executionContext?: ExecutionContext;
}
export interface HttpDispatcherResult {
handled: boolean;
response?: {
status: number;
body?: any;
headers?: Record<string, string>;
};
result?: any; // For flexible return types or direct response objects (Response/NextResponse)
}
/**
* ADR-0006 generic kernel-resolution seam.
*
* A host (e.g. ObjectStack Cloud) injects a resolver to own per-request
* kernel selection. The framework ships NO multi-tenant implementation — all
* hostname→env strategy, the per-env kernel cache, and the control plane live
* in the host distribution (`@objectstack/objectos-runtime`). When no resolver
* is injected the dispatcher serves every request from its single
* `defaultKernel` (single-environment mode).
*
* Returning `undefined` routes the request to `defaultKernel` — resolvers use
* this for control-plane / unscoped / single-environment requests.
*
* As of ADR-0006 Phase 5 the resolver owns the ENTIRE per-request environment
* resolution, not just kernel selection: the dispatcher no longer performs any
* hostname / header / session → environment lookup of its own. The dispatcher
* provides parsing hints on the context (`routePath`, `urlEnvironmentId`) and
* expects the resolver to SET `context.environmentId` (and optionally
* `context.dataDriver`) for scoped requests — downstream dispatcher stages
* (project-membership enforcement, scope TTL touch, scoped service resolution)
* key off `context.environmentId`.
*/
export interface KernelResolver {
resolveKernel(
context: HttpProtocolContext,
defaultKernel: ObjectKernel,
): Promise<ObjectKernel | undefined> | ObjectKernel | undefined;
}
/**
* Optional configuration passed to the dispatcher constructor. Supports the
* legacy `enforceProjectMembership` toggle plus the new multi-kernel
* scheduling hook required by ADR-0003's cloud runtime mode.
*/
export interface HttpDispatcherOptions {
enforceProjectMembership?: boolean;
/**
* Optional generic kernel-resolution seam (ADR-0006). The SOLE
* multi-tenant hook: the host's resolver owns env resolution + kernel
* selection per request (see {@link KernelResolver}). Falls back to
* `resolveService('kernel-resolver')`. Hosts that register none run
* single-environment on `defaultKernel`. (The legacy `kernelManager`
* option and the dispatcher's built-in hostname/header/session
* resolution were removed in ADR-0006 Phase 5 — that strategy lives in
* the cloud distribution's resolver now.)
*/
kernelResolver?: KernelResolver;
/**
* Optional {@link EnvironmentScopeManager}. When present, `touch(environmentId)` is
* called on every scoped request so idle projects are evicted after TTL.
*/
scopeManager?: EnvironmentScopeManager;
/**
* Reject anonymous requests to `auth: true` service routes (AI) and to the
* metadata catch-all with HTTP 401, mirroring the REST API's `requireAuth`
* gate. Matches {@link DispatcherPluginConfig.requireAuth}; the dispatcher
* plugin threads the host's `api.requireAuth` here. Defaults to `false`
* (backward-compatible — nothing enforced `RouteDefinition.auth` before).
*/
requireAuth?: boolean;
}
/**
* The HTTP dispatch engine — translates an inbound (method, path, body, ctx)
* request into a kernel response. Used directly by the framework's HTTP adapters
* (express / fastify / nextjs / nestjs / nuxt / sveltekit / hono) and plugin-msw,
* which need a *callable* dispatcher.
*
* NOTE: `createDispatcherPlugin()` is a different thing — a kernel plugin that
* registers routes on a kernel-hosted HTTP server. It is NOT a drop-in for
* adapters. Retiring this public class behind a `createHttpDispatcher()` factory
* is tracked in #2380 (a deliberate adapter-API change, not yet done) — so this
* is intentionally NOT marked `@deprecated` while no working replacement exists.
*/
export class HttpDispatcher {
private kernel: any; // Casting to any to access dynamic props like services, graphql
private defaultKernel: ObjectKernel;
private defaultProject?: { environmentId: string; orgId?: string };
private kernelResolver?: KernelResolver;
private scopeManager?: EnvironmentScopeManager;
/**
* When `true`, scoped data-plane routes enforce a
* `sys_environment_member` lookup and return 403 for non-members.
* Defaults to `true` when a environmentId is resolvable — legacy callers
* can opt out via the third constructor argument (see
* `DispatcherConfig.enforceProjectMembership`).
*/
private enforceMembership: boolean;
/**
* When `true`, `auth: true` AI routes and the metadata catch-all reject
* anonymous callers with 401 (mirrors the REST `requireAuth` gate). Set
* from {@link HttpDispatcherOptions.requireAuth}. Defaults to `false`.
*/
private requireAuth: boolean;
/**
* In-memory cache of positive membership checks, keyed by
* `${environmentId}:${userId}`. Entries expire 60 seconds after insertion
* — a short TTL is acceptable because a user whose access was just
* revoked sees stale access for at most one minute.
*/
private membershipCache: Map<string, number> = new Map();
private static readonly MEMBERSHIP_CACHE_TTL_MS = 60_000;
/** Well-known system project id — bypassed for any authenticated user. */
private static readonly SYSTEM_ENVIRONMENT_ID = '00000000-0000-0000-0000-000000000001';
/** Well-known platform org id — members bypass project membership. */
private static readonly PLATFORM_ORG_ID = '00000000-0000-0000-0000-000000000000';
/**
* @param _envRegistryIgnored — RETIRED (ADR-0006 Phase 5). Environment
* resolution moved behind the host's {@link KernelResolver}; the
* positional parameter is kept so existing 3-arg callers keep compiling,
* but its value is ignored.
*/
constructor(kernel: ObjectKernel, _envRegistryIgnored?: unknown, options?: HttpDispatcherOptions) {
this.kernel = kernel;
this.defaultKernel = kernel;
const resolveService = (name: string): any => {
try { return (kernel as any).getService?.(name); } catch { return undefined; }
};
this.enforceMembership = options?.enforceProjectMembership ?? true;
this.requireAuth = options?.requireAuth ?? false;
// ADR-0006 kernel-resolution seam — the host's resolver owns env
// resolution + kernel selection. Optional service so single-environment
// hosts that register none are unchanged.
this.kernelResolver = options?.kernelResolver ?? resolveService('kernel-resolver');
this.scopeManager = options?.scopeManager ?? resolveService('scope-manager');
// Single-project default is resolved lazily on first request — the
// plugin that registers it (`createSingleEnvironmentPlugin`) may run
// its `init()` after the HttpDispatcher is constructed.
}
private resolveDefaultProject(): { environmentId: string; orgId?: string } | undefined {
if (this.defaultProject) return this.defaultProject;
try {
const v = (this.kernel as any).getService?.('default-project');
if (v?.environmentId) {
this.defaultProject = v;
return v;
}
} catch {
// service not registered — single-environment plugin not in stack
}
return undefined;
}
/**
* Resolve the per-request identity/session, timed as the `auth`
* `Server-Timing` span — the prime suspect for unexplained data-API
* overhead (session lookup, org-scope resolution). A no-op wrapper when
* perf-tuning is off, so it costs nothing on the normal path.
*/
private async timedResolveExecutionContext(
opts: Parameters<typeof resolveExecutionContext>[0],
): Promise<ExecutionContext> {
const ec = await measureServerTiming('auth', () => resolveExecutionContext(opts), 'Identity/session');
// Perf-tuning disclosure gate (#2408): when timing was opened
// per-request via `X-OS-Debug-Timing`, the `Server-Timing` header stays
// withheld until the request proves an admin/service identity — never
// leak phase timings to an ordinary caller. A no-op when perf-tuning is
// off or already global (no gate, or gate already open).
if (isPerfDisclosurePrincipal(ec)) allowPerfDisclosure();
return ec;
}
private success(data: any, meta?: any) {
return {
status: 200,
body: { success: true, data, meta }
};
}
private error(message: string, code: number = 500, details?: any) {
return {
status: code,
body: { success: false, error: { message, code, details } }
};
}
/**
* Build an error response from a THROWN service/protocol error, preserving
* the error's own HTTP `status` and — critically — any structured `issues`
* array (e.g. spec-validation `{ path, message, code }[]` from
* `protocol.saveMetaItem`). The plain `error(msg, code)` path collapses a
* validation failure to a single message, so the UI can only show a generic
* banner; carrying `issues` (and the semantic `code`) in `details` lets it
* map each error back to the offending field. Falls back to `fallbackStatus`
* and behaves exactly like `error()` for errors that carry neither.
*/
private errorFromThrown(e: any, fallbackStatus = 500) {
const status =
typeof e?.status === 'number' ? e.status
: typeof e?.statusCode === 'number' ? e.statusCode
: fallbackStatus;
const issues = Array.isArray(e?.issues) ? e.issues : undefined;
const details =
issues || e?.code
? { ...(e?.code ? { code: e.code } : {}), ...(issues ? { issues } : {}) }
: undefined;
return this.error(e?.message ?? String(e), status, details);
}
/**
* ADR-0046: `doc` list responses omit `content` by default — manuals
* are the one metadata payload that grows unbounded, and the list
* surface only needs `name` + `label`. `?include=content` opts back in
* (single-item GET /metadata/doc/:name always returns the full body).
*/
private slimDocList(type: string, data: any, query?: Record<string, string>): any {
if (type !== 'doc' || query?.include === 'content') return data;
const strip = (items: any[]) =>
items.map((i) => {
if (!i || typeof i !== 'object') return i;
const { content: _content, ...rest } = i as Record<string, unknown>;
return rest;
});
if (Array.isArray(data)) return strip(data);
if (data && Array.isArray(data.items)) return { ...data, items: strip(data.items) };
return data;
}
/**
* 404 Route Not Found — no route is registered for this path.
*/
private routeNotFound(route: string) {
return {
status: 404,
body: {
success: false,
error: {
code: 404,
message: `Route Not Found: ${route}`,
type: 'ROUTE_NOT_FOUND' as const,
route,
hint: 'No route is registered for this path. Check the API discovery endpoint for available routes.',
},
},
};
}
/**
* Direct data service dispatch — replaces broker.call('data.*').
* Tries protocol service first (supports expand/populate), falls back to ObjectQL.
*
* @param dataDriver - Optional environment-scoped driver to use instead of kernel default
* @param scopeId - Optional project ID for scoped service resolution (SharedProjectPlugin mode)
*/
private async callData(
action: string,
params: any,
dataDriver?: any,
scopeId?: string,
executionContext?: ExecutionContext,
): Promise<any> {
// ── Object-level API exposure gate (ADR-0049, #1889) ─────
// Honour the object's `apiEnabled` / `apiMethods` declarations for
// external traffic. System/internal contexts bypass — these flags
// govern API *exposure*, not internal engine self-writes.
if (!executionContext?.isSystem && params?.object) {
let def: any;
try {
const meta = await this.resolveService('metadata', scopeId);
def = await (meta as any)?.getObject?.(params.object);
} catch {
def = undefined; // fall open to schema defaults (apiEnabled=true)
}
const gate = checkApiExposure(def, action);
if (!gate.allowed) {
throw { statusCode: gate.status ?? 403, message: gate.reason ?? 'API access denied' };
}
}
const protocol = await this.resolveService('protocol', scopeId);
const qlService = dataDriver ?? await this.getObjectQLService(scopeId);
const ql = qlService ?? await this.resolveService('objectql', scopeId);
const qlOpts = executionContext ? { context: executionContext } : undefined;
const findOpts = (extra?: any) => {
const base = qlOpts ? { ...qlOpts } : {};
return extra ? { ...base, ...extra } : (qlOpts ? base : undefined);
};
if (action === 'create') {
// Prefer the protocol service (validations + RLS + audit), mirroring
// the read paths below. The MCP bridge passes `context.dataDriver` as
// `ql`, which in the multi-env runtime is a RAW db driver with no ORM
// `insert` — so going straight to `ql.insert` broke MCP create_record
// ("ql.insert is not a function") while REST (which uses `createData`)
// worked. Routing writes through the protocol keeps them aligned.
if (protocol && typeof protocol.createData === 'function') {
return await protocol.createData({ object: params.object, data: params.data, ...(scopeId ? { environmentId: scopeId } : {}), context: executionContext });
}
if (ql && typeof ql.insert === 'function') {
const res = await ql.insert(params.object, params.data, qlOpts);
const record = { ...params.data, ...res };
return { object: params.object, id: record.id, record };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'get') {
if (protocol && typeof protocol.getData === 'function') {
return await protocol.getData({ object: params.object, id: params.id, expand: params.expand, select: params.select, context: executionContext });
}
if (ql) {
let all = await ql.find(params.object, findOpts({ where: { id: params.id }, limit: 1 }));
if (all && (all as any).value) all = (all as any).value;
if (!all) all = [];
const match = (all as any[]).find((i: any) => i.id === params.id);
return match ? { object: params.object, id: params.id, record: match } : null;
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'update') {
if (protocol && typeof protocol.updateData === 'function') {
return await protocol.updateData({ object: params.object, id: params.id, data: params.data, ...(scopeId ? { environmentId: scopeId } : {}), context: executionContext });
}
if (ql && params.id && typeof ql.update === 'function') {
let all = await ql.find(params.object, findOpts({ where: { id: params.id }, limit: 1 }));
if (all && (all as any).value) all = (all as any).value;
if (!all) all = [];
const existing = (all as any[]).find((i: any) => i.id === params.id);
if (!existing) throw new Error('[ObjectStack] Not Found');
await ql.update(params.object, params.data, findOpts({ where: { id: params.id } }));
return { object: params.object, id: params.id, record: { ...existing, ...params.data } };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'delete') {
if (protocol && typeof protocol.deleteData === 'function') {
return await protocol.deleteData({ object: params.object, id: params.id, ...(scopeId ? { environmentId: scopeId } : {}), context: executionContext });
}
if (ql && typeof ql.delete === 'function') {
await ql.delete(params.object, findOpts({ where: { id: params.id } }));
return { object: params.object, id: params.id, deleted: true };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'query' || action === 'find') {
if (protocol && typeof protocol.findData === 'function') {
// Build query: use explicit params.query if provided, otherwise extract query fields from params
const query = params.query || (() => {
const { object, ...rest } = params;
return rest;
})();
return await protocol.findData({ object: params.object, query, context: executionContext });
}
if (ql) {
let all = await ql.find(params.object, qlOpts);
if (!Array.isArray(all) && all && (all as any).value) all = (all as any).value;
if (!all) all = [];
return { object: params.object, records: all, total: all.length };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'aggregate') {
// Aggregate MUST run through the ObjectQL ENGINE (never the raw
// `dataDriver` the MCP bridge threads through for the other verbs):
// only the engine's middleware chain injects RLS/tenant scoping and
// the FLS aggregate-input gate. A raw driver.aggregate() would
// evaluate the query verbatim over every row.
//
// At least one aggregation is REQUIRED: with neither aggregations
// nor groupBy the engine's in-memory path degrades to raw rows,
// and the FLS result masker does not cover the `aggregate` op —
// grouped/aggregated output must stay the only thing this action
// can ever return.
if (!Array.isArray(params.aggregations) || params.aggregations.length === 0) {
throw { statusCode: 400, message: 'aggregate requires at least one aggregation' };
}
const engine = (await this.getObjectQLService(scopeId))
?? await this.resolveService('objectql', scopeId).catch(() => null);
if (engine && typeof engine.aggregate === 'function') {
const rows = await engine.aggregate(
params.object,
{
...(params.where ? { where: params.where } : {}),
...(params.groupBy ? { groupBy: params.groupBy } : {}),
...(params.aggregations ? { aggregations: params.aggregations } : {}),
...(params.timezone ? { timezone: params.timezone } : {}),
...(executionContext ? { context: executionContext } : {}),
},
);
return { object: params.object, rows: rows ?? [] };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'batch') {
// Batch operations — not yet supported via direct service dispatch
return { object: params.object, results: [] };
}
throw { statusCode: 400, message: `Unknown data action: ${action}` };
}
/**
* Handle an MCP request over the Streamable HTTP transport (`/mcp`).
*
* Gating + auth (fail-closed):
* - **default-on**: served unless `OS_MCP_SERVER_ENABLED=false` (single-env
* runtime; MCP is a core platform capability). Multi-tenant cloud
* overrides this gate per env. When opted out we return 404 so the
* surface isn't advertised.
* - **auth**: requires a principal already resolved by
* `resolveExecutionContext` (the `sys_api_key` Bearer/header path or a
* session). Anonymous → 401.
*
* Execution: the MCP runtime builds a stateless per-request server whose
* object-CRUD tools run through {@link callData} bound to THIS request's
* ExecutionContext — i.e. the exact permission + RLS path the REST API
* uses. An external agent can never exceed the key's authority.
*/
async handleMcp(body: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
if (!HttpDispatcher.isMcpEnabled()) {
return { handled: true, response: this.error('MCP server is not enabled for this environment', 404) };
}
const mcp: any = await this.resolveService('mcp', context.environmentId);
if (!mcp || typeof mcp.handleHttpRequest !== 'function') {
return { handled: true, response: this.error('MCP server is not available', 501) };
}
const ec = context.executionContext;
if (!ec || (!ec.userId && !ec.isSystem)) {
// Per the MCP authorization spec (RFC 9728 §5.1), a 401 from the
// protected resource advertises where its metadata lives so an
// OAuth-capable client can bootstrap discovery → DCR → PKCE.
// Only advertised when the OAuth track is actually live (AS on +
// TLS rule satisfied); API-key-only deployments return a plain 401.
const resourceMetadataUrl = await this.getMcpResourceMetadataUrl(context);
const response = this.error(
resourceMetadataUrl
? 'Unauthorized: a valid OAuth access token or API key is required'
: 'Unauthorized: a valid API key is required',
401,
) as { status: number; body: any; headers?: Record<string, string> };
if (resourceMetadataUrl) {
response.headers = {
'WWW-Authenticate':
`Bearer realm="ObjectStack MCP", resource_metadata="${resourceMetadataUrl}"`,
};
}
return { handled: true, response };
}
// ── OAuth scope → tool-family enforcement (fail-closed, #2698) ──
// `oauthScopes` is set ONLY for OAuth-token provenance. A token that
// grants none of the MCP tool families gets 403 insufficient_scope
// up front; a partial grant narrows the tool set at registration
// time inside the MCP runtime. API-key / session principals
// (`oauthScopes` undefined) keep the full principal-bound surface.
const grantedScopes = Array.isArray((ec as any).oauthScopes)
? ((ec as any).oauthScopes as string[])
: undefined;
if (grantedScopes && !grantedScopes.some((s) => (MCP_OAUTH_SCOPES as readonly string[]).includes(s))) {
const resourceMetadataUrl = await this.getMcpResourceMetadataUrl(context);
const response = this.error(
`Forbidden: the access token grants none of the MCP scopes (${MCP_OAUTH_SCOPES.join(', ')})`,
403,
) as { status: number; body: any; headers?: Record<string, string> };
response.headers = {
'WWW-Authenticate':
'Bearer error="insufficient_scope"' +
`, scope="${MCP_OAUTH_SCOPES.join(' ')}"` +
(resourceMetadataUrl ? `, resource_metadata="${resourceMetadataUrl}"` : ''),
};
return { handled: true, response };
}
// The MCP transport needs a Web-standard Request. The runtime HTTP
// adapter may hand us a node/Hono-style req (plain `headers` object,
// path-only `url`), so normalise it.
const webRequest = this.toMcpWebRequest(context.request, body);
if (!webRequest) {
return { handled: true, response: this.error('MCP transport requires a standard HTTP request', 400) };
}
const bridge = this.buildMcpBridge(context);
let webRes: Response;
try {
webRes = await mcp.handleHttpRequest(webRequest, {
bridge,
parsedBody: body,
// undefined = not scope-limited (API key / session); an array
// narrows the registered tool families inside the MCP runtime.
...(grantedScopes ? { toolOptions: { grantedScopes } } : {}),
});
} catch (err: any) {
return { handled: true, response: this.error(err?.message ?? 'MCP request failed', 500) };
}
// Convert the transport's buffered Web Response into the dispatcher's
// `{ status, headers, body }` shape (JSON-response mode → fully buffered).
const headers: Record<string, string> = {};
try { webRes.headers.forEach((v, k) => { headers[k] = v; }); } catch { /* no headers */ }
const text = await webRes.text().catch(() => '');
let responseBody: any = null;
if (text) {
const ct = headers['content-type'] ?? '';
if (ct.includes('application/json')) {
try { responseBody = JSON.parse(text); } catch { responseBody = text; }
} else {
responseBody = text;
}
}
return { handled: true, response: { status: webRes.status, headers, body: responseBody } };
}
/**
* Whether the MCP HTTP surface is on for this single-env runtime.
* Default-on core capability; `OS_MCP_SERVER_ENABLED=false` opts out
* (single decision point: `isMcpServerEnabled` in `@objectstack/types`).
*/
private static isMcpEnabled(): boolean {
return isMcpServerEnabled();
}
/**
* Absolute URL of the RFC 9728 protected-resource metadata for the MCP
* endpoint, advertised via `WWW-Authenticate` (#2698). `null` when the
* OAuth track is off — the auth service owns the decision (AS enabled +
* OAuth 2.1 TLS rule), the dispatcher only relays it. Never throws.
*/
private async getMcpResourceMetadataUrl(context: HttpProtocolContext): Promise<string | null> {
try {
const authService: any = await this.resolveService('auth', context.environmentId);
const url = authService?.getMcpResourceMetadataUrl?.();
return typeof url === 'string' && url ? url : null;
} catch {
return null;
}
}
/**
* `GET /mcp/skill` — the environment-customized portable Agent Skill
* (`SKILL.md`), rendered by the MCP service (ADR-0036 Amendment C: ONE
* generic skill; only the connection URL is environment-specific).
*
* Served PUBLIC like `/discovery`: the content is generic agent
* instructions plus a URL the caller already knows — no schema, no
* tenant data. Gated on the same default-on switch as the `/mcp` route
* (404 when opted out, so the surface isn't advertised) and 501 when the
* MCP plugin isn't loaded, mirroring `handleMcp`.
*/
async handleMcpSkill(method: string, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
if (!HttpDispatcher.isMcpEnabled()) {
return { handled: true, response: this.error('MCP server is not enabled for this environment', 404) };
}
if (method !== 'GET') {
return {
handled: true,
response: {
status: 405,
headers: { Allow: 'GET' },
body: { success: false, error: { message: 'Method not allowed — use GET', code: 405 } },
},
};
}
const mcp: any = await this.resolveService('mcp', context.environmentId);
if (!mcp || typeof mcp.renderSkill !== 'function') {
return { handled: true, response: this.error('MCP server is not available', 501) };
}
// Resolve this environment's MCP URL for the skill's Connect section:
// the auth service owns the canonical value (base URL config); fall
// back to deriving from the request host so the endpoint still works
// when the auth plugin isn't loaded.
let mcpUrl: string | undefined;
try {
const authService: any = await this.resolveService('auth', context.environmentId);
const url = authService?.getMcpResourceUrl?.();
if (typeof url === 'string' && url) mcpUrl = url;
} catch { /* fall through to host derivation */ }
if (!mcpUrl) {
try {
const webReq = this.toMcpWebRequest(context.request, undefined);
const host = webReq?.headers.get('host');
if (host) {
const proto = webReq?.headers.get('x-forwarded-proto') || 'http';
mcpUrl = `${proto}://${host}/api/v1/mcp`;
}
} catch { /* leave the documented placeholder in place */ }
}
const markdown: string = mcp.renderSkill({ mcpUrl });
// Raw text must NOT ride the `response` channel — `sendResult` JSON-
// encodes those bodies unconditionally. The `result` stream channel is
// the one raw pipe through every adapter (string events are written
// verbatim, custom headers honored), so serve the markdown as a
// single-chunk "stream".
return {
handled: true,
result: {
type: 'stream',
status: 200,
contentType: 'text/markdown; charset=utf-8',
headers: {
'content-type': 'text/markdown; charset=utf-8',
'content-disposition': 'inline; filename="SKILL.md"',
// Same reasoning as /discovery (cloud#152): reflects mutable
// runtime config (base URL), must never be edge-cached stale.
'cache-control': 'no-store',
},
events: (async function* () {
yield markdown;
})(),
},
} as any;
}
/**
* Normalise the inbound request into a Web-standard `Request` for the MCP
* transport. Accepts an already-Web `Request`, or a node/Hono-style req
* (plain `headers` object, path-only `url`). Returns undefined only if the
* shape is unusable. The body is carried separately via `parsedBody`, so a
* GET/DELETE (no body) and a POST (JSON-RPC) both normalise cleanly.
*/
private toMcpWebRequest(raw: any, parsedBody: any): Request | undefined {
if (!raw) return undefined;
// Already a Web Request.
if (typeof raw.headers?.get === 'function' && typeof raw.url === 'string' && typeof raw.method === 'string') {
return raw as Request;
}
try {
const method = String(raw.method ?? 'POST').toUpperCase();
// Normalise headers (plain object or Headers-like).
const headers = new Headers();
const h = raw.headers;
if (h) {
if (typeof h.forEach === 'function') {
h.forEach((v: any, k: any) => { if (v != null) headers.set(String(k), String(v)); });
} else {
for (const k of Object.keys(h)) {
const v = (h as any)[k];
if (v != null) headers.set(k, Array.isArray(v) ? v.join(',') : String(v));
}
}
}
// Build an absolute URL (node req.url is path-only).
let url: string;
try {
url = new URL(String(raw.url)).toString();
} catch {
const host = headers.get('host') || 'mcp.local';
const path = typeof raw.url === 'string' && raw.url ? raw.url : '/api/v1/mcp';
url = `https://${host}${path.startsWith('/') ? path : `/${path}`}`;
}
const init: { method: string; headers: Headers; body?: string } = { method, headers };
if (method !== 'GET' && method !== 'HEAD' && method !== 'DELETE') {
init.body = typeof parsedBody === 'string' ? parsedBody : JSON.stringify(parsedBody ?? {});
}
return new Request(url, init);
} catch {
return undefined;
}
}
/**
* Build a principal-bound {@link McpDataBridge}: every method runs AS the
* request's ExecutionContext through {@link callData} (RLS/permissions) and
* the per-env metadata service. Keeps the MCP tool layer free of any direct
* engine access.
*/
private buildMcpBridge(context: HttpProtocolContext): any {
const ec = context.executionContext;
const envId = context.environmentId;
const driver = (context as any).dataDriver;
const callData = this.callData.bind(this);
const getMeta = () => this.resolveService('metadata', envId);
return {
listObjects: async () => {
const meta: any = await getMeta();
const objs: any[] = (await meta?.listObjects?.()) ?? [];
return objs.map((o) => ({
name: o.name,
label: o.label ?? o.name,
fieldCount: o.fields ? Object.keys(o.fields).length : undefined,
}));
},
describeObject: async (name: string) => {
const meta: any = await getMeta();
const def: any = await meta?.getObject?.(name);
if (!def) return null;
const fields = def.fields ?? {};
return {
name: def.name,
label: def.label ?? def.name,
fields: Object.entries(fields).map(([k, f]: [string, any]) => ({
name: k,
type: f?.type,
label: f?.label ?? k,
required: f?.required ?? false,
})),
enableFeatures: def.enable ?? {},
};
},
query: async (object: string, o: any) => {
const query: any = {};
if (o?.where) query.where = o.where;
if (o?.fields) query.fields = o.fields;
if (typeof o?.limit === 'number') query.limit = o.limit;
if (typeof o?.offset === 'number') query.offset = o.offset;
if (o?.orderBy) query.orderBy = o.orderBy;
return await callData('query', { object, query }, driver, envId, ec);
},
get: async (object: string, id: string) => {
const res: any = await callData('get', { object, id }, driver, envId, ec);
return res?.record ?? res ?? null;
},
aggregate: async (object: string, o: any) => {
// NOTE: `driver` (the raw per-env db driver) is deliberately NOT
// passed — callData's aggregate branch resolves the ObjectQL
// engine itself so the security middleware (RLS + FLS aggregate
// gate) always runs. See the branch comment in callData.
const res: any = await callData(
'aggregate',
{
object,
where: o?.where,
groupBy: o?.groupBy,
aggregations: o?.aggregations,
timezone: o?.timezone,
},
undefined,
envId,
ec,
);
return res?.rows ?? [];
},
create: async (object: string, data: any) =>
await callData('create', { object, data }, driver, envId, ec),
update: async (object: string, id: string, data: any) =>
await callData('update', { object, id, data }, driver, envId, ec),
remove: async (object: string, id: string) =>
await callData('delete', { object, id }, driver, envId, ec),
// ── Business-action surface (McpActionBridge) ──────────────
// Resolution + dispatch flow through the framework's own action
// mechanism (engine.executeAction / automation flow runner). All
// gating is at INVOKE time — `ai.exposed` (author opt-in, #2849) +
// the ADR-0066 D4 capability gate + record load under the caller's
// RLS. Script/body handlers then run TRUSTED (see
// buildActionEngineFacade); flows honour `runAs` with the caller's
// identity forwarded. No `@objectstack/service-ai`.
listActions: async () => {
const meta: any = await getMeta();
const hasAutomation = Boolean(
await this.resolveService('automation', envId).catch(() => null),
);
const out: any[] = [];
for (const { action, objectName, obj } of await this.collectActionDeclarations(meta)) {
if (!objectName || isSystemObjectName(objectName)) continue; // fail-closed on sys_*
if (!this.isHeadlessInvokableAction(action, hasAutomation)) continue;
// [#2849 / ADR-0011] MCP is an AI surface: only actions the
// author explicitly opted in via `ai.exposed` are listed.
// Fail-closed — bodies run as trusted code (see
// buildActionEngineFacade), so author opt-in is the boundary.
if (this.actionAiExposureError(action)) continue;
// Hide actions the caller is not permitted to run.
if (this.actionPermissionError(action, ec)) continue;
out.push(this.summarizeAction(action, obj, objectName));
}
return out;
},
runAction: async (
name: string,
input: { objectName?: string; recordId?: string; params?: Record<string, unknown> },
) => this.invokeBusinessAction(name, input ?? {}, { driver, envId, ec, getMeta, callData }),
};
}
// ── MCP action bridge helpers ──────────────────────────────────────
/**
* [ADR-0066 D4] Shared capability gate for an action invocation. Returns a
* human-readable error string when the caller's `systemPermissions` don't
* cover the action's declared `requiredPermissions`, or `null` when allowed.
* System/engine self-invocation (`isSystem`) bypasses; an action without
* `requiredPermissions` is ungated. Single-sourced so the REST `/actions/...`
* route and the MCP `run_action` bridge enforce the SAME declaration.
*/
private actionPermissionError(actionDef: any, ec: any, objectName?: string): string | null {
const required: string[] = Array.isArray(actionDef?.requiredPermissions)
? actionDef.requiredPermissions
: [];
if (required.length === 0) return null;
if (ec?.isSystem) return null;
const held = new Set<string>(ec?.systemPermissions ?? []);
const missing = required.filter((perm) => !held.has(perm));
if (missing.length === 0) return null;
const on = objectName ? ` on '${objectName}'` : '';
return (
`Action '${actionDef?.name ?? 'unknown'}'${on} requires capability ` +
`[${required.join(', ')}] — caller is missing [${missing.join(', ')}]`
);
}
/**
* [#2849 / ADR-0011] AI-exposure gate for the MCP action surface. Returns a
* human-readable error string unless the action's author explicitly opted it
* into the AI surface with `ai.exposed: true`, or `null` when exposed.
*
* This gate is the REAL agent-facing boundary for actions: script/body
* handlers execute as TRUSTED application code (the engine facade carries no
* ExecutionContext — see {@link buildActionEngineFacade}), so once invoked, a
* body's reads/writes are NOT bounded by the caller's RLS/FLS or an agent's
* data ceiling (ADR-0090 D10). The author's explicit opt-in — not a data-layer
* backstop — therefore decides what AI may trigger. Fail-closed by default.
*/
private actionAiExposureError(actionDef: any, objectName?: string): string | null {
if (actionDef?.ai?.exposed === true) return null;
const on = objectName ? ` on '${objectName}'` : '';
return (
`Action '${actionDef?.name ?? 'unknown'}'${on} is not exposed to AI — ` +
`the app author must opt it in with \`ai: { exposed: true, description: … }\``
);
}
/**
* Whether an action has a headless invocation path (so MCP can run it).
* Mirrors the supported-type set of the (now cloud-side) action-tools
* bridge: `script` needs a handler binding (`target`) or an inline `body`;
* `flow` needs a `target` and an automation service. UI-only types
* (`url`, `modal`, `form`) and `api` have no server dispatch here.
*/
private isHeadlessInvokableAction(action: any, hasAutomation: boolean): boolean {
const type: string = action?.type ?? 'script';
if (type === 'script') return Boolean(action?.target || action?.body);
if (type === 'flow') return Boolean(action?.target) && hasAutomation;
return false;
}
/** True when an action is destructive by author signal/heuristic (HITL hint). */
private actionLooksDestructive(action: any): boolean {
if (action?.ai?.requiresConfirmation !== undefined) return Boolean(action.ai.requiresConfirmation);
return Boolean(action?.confirmText || action?.mode === 'delete' || action?.variant === 'danger');
}
/** Project an action's declarative metadata into a lean MCP summary. */
private summarizeAction(action: any, obj: any, objectName: string): any {
const requiresRecord =
Array.isArray(action?.locations) &&
action.locations.some(
(l: string) =>
l === 'list_item' || l === 'record_header' || l === 'record_more' || l === 'record_related',
);
const description =
(typeof action?.ai?.description === 'string' ? action.ai.description : undefined) ??
(typeof action?.label === 'string' ? action.label : undefined);
const params = this.summarizeActionParams(action, obj);
return {
name: action.name,
objectName,
...(typeof action?.label === 'string' ? { label: action.label } : {}),
...(description ? { description } : {}),
type: action?.type ?? 'script',
requiresRecord: Boolean(requiresRecord),
requiresConfirmation: this.actionLooksDestructive(action),
...(params.length > 0 ? { params } : {}),
};
}
/** Map an ObjectStack field type to a JSON-Schema primitive (conservative). */
private jsonTypeOf(t: string | undefined): 'string' | 'number' | 'boolean' | 'array' {
switch (t) {
case 'number': case 'currency': case 'percent': case 'rating': case 'slider': case 'autonumber':
return 'number';
case 'boolean': case 'toggle':
return 'boolean';
case 'multiselect': case 'checkboxes': case 'tags':
return 'array';
default:
return 'string';
}
}
/** Resolve an action's params into LLM-facing summaries (field-backed types resolved). */
private summarizeActionParams(action: any, obj: any): any[] {
const fields: Record<string, any> = obj?.fields ?? {};
const out: any[] = [];
for (const p of (Array.isArray(action?.params) ? action.params : [])) {
const fieldRef: string | undefined = p?.field;
const field = fieldRef ? fields[fieldRef] : undefined;
const name: string | undefined = p?.name ?? fieldRef;
if (!name) continue;
const type = this.jsonTypeOf(p?.type ?? field?.type);
const label = typeof p?.label === 'string' ? p.label : field?.label;
const help = p?.helpText ?? field?.description;
const description = [label, help].filter(Boolean).join(' — ') || undefined;
const optionSource = p?.options ?? field?.options;
const enumVals = Array.isArray(optionSource)
? optionSource
.map((o: any) => (typeof o === 'string' ? o : o?.value))
.filter((v: any): v is string => typeof v === 'string')
: [];
out.push({
name,
type,
required: Boolean(p?.required ?? field?.required ?? false),
...(description ? { description } : {}),
...(enumVals.length > 0 ? { enum: enumVals } : {}),
});
}