-
Notifications
You must be signed in to change notification settings - Fork 446
Expand file tree
/
Copy pathclient-capability-coordinator.ts
More file actions
1750 lines (1666 loc) · 62 KB
/
Copy pathclient-capability-coordinator.ts
File metadata and controls
1750 lines (1666 loc) · 62 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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { createHash } from 'node:crypto';
import { AsyncLocalStorage } from 'node:async_hooks';
import {
buildMcpTools,
mcpProxyToolName,
type McpPreparedToolCall,
type McpToolProvider,
} from '@maka/runtime/mcp-tools';
import { type MakaTool } from '@maka/runtime/tool-runtime';
import type { RootExecutionDescriptor } from '@maka/core/runtime-invocation';
import {
clientCapabilityScopeIdentity,
type ClientCapabilityGrantTarget,
} from '@maka/core/client-capability-grant';
import { type ToolGroup } from '@maka/runtime/tool-availability';
import type { InteractiveInteractionStoreWriterFacade } from '@maka/storage/interaction-store';
import {
type ClientCapabilityOffer,
type ClientCapabilityAdmissionEvidence,
type ClientCapabilityOwnerIdentity,
type ClientCapabilityReplaceInput,
type ClientCapabilityServiceOffer,
type ClientCapabilityToolDescriptor,
type ClientCapabilityUnregisterInput,
} from '../protocol/index.js';
import {
ClientCapabilityInvocationBroker,
ClientCapabilityInvocationError,
type ClientCapabilityInvocationFailure,
} from './client-capability-invocation-broker.js';
import type {
ClientCapabilityOperationHandlerMap,
ConnectionContext,
} from './operation-dispatcher.js';
import type { RuntimePolicyActivationGate } from './runtime-policy-activation-gate.js';
import type {
ClientCapabilityConnectionIdentity,
ClientCapabilityConnection,
ClientCapabilityConnectionSender,
ClientCapabilityService,
} from './client-capability-service.js';
import type { HostInteractionCoordinator } from './interaction-coordinator.js';
import { clientCapabilityProviderId } from './client-capability-provider-id.js';
// Leave the Host deadline outside the provider's bounded action deadline so an
// accepted call can return its real terminal result instead of outcome_unknown.
const DEFAULT_CALL_TIMEOUT_MS = 150_000;
const DESKTOP_BROWSER_SERVER_ID = 'desktop_browser';
const DESKTOP_SETTINGS_SERVER_ID = 'desktop_settings';
const DESKTOP_MCP_OFFER_PREFIX = 'desktop_mcp';
const DESKTOP_BROWSER_TOOLS = new Set([
'browser_navigate',
'browser_snapshot',
'browser_click',
'browser_type',
'browser_wait',
'browser_extract',
]);
const DESKTOP_SETTINGS_TOOLS = new Set(['MakaClientSettingsGet', 'MakaClientSettingsUpdate']);
export { ClientCapabilityInvocationError };
export type { ClientCapabilityInvocationFailure };
export interface ClientCapabilitySnapshot {
readonly registrationIds: readonly string[];
readonly groups: readonly ToolGroup[];
readonly tools: readonly MakaTool[];
release(): void;
}
interface ClientProviderState {
readonly providerId: string;
readonly principalId: string;
readonly clientInstanceId: string;
readonly credentialBoundClientInstanceId?: string;
readonly principalKind: ClientCapabilityConnectionIdentity['principalKind'];
readonly trustedProvider: boolean;
readonly capabilityOwner?: ClientCapabilityOwnerIdentity;
activeConnectionId?: string;
current?: CapabilityRegistration;
readonly registrations: Map<string, CapabilityRegistration>;
}
interface ClientProviderConnection {
readonly connectionId: string;
readonly provider: ClientProviderState;
readonly sender: ClientCapabilityConnectionSender;
superseded: boolean;
}
interface CapabilityRegistration {
readonly providerId: string;
readonly connectionId: string;
readonly registrationId: string;
readonly trustedProvider: boolean;
readonly offersByContract: ReadonlyMap<string, FrozenOfferBinding>;
readonly servicesByContract: ReadonlyMap<string, ClientCapabilityServiceOffer>;
snapshotRefs: number;
}
interface FrozenOfferBinding {
readonly contractId: string;
readonly offer: ClientCapabilityOffer;
readonly toolsByIdentity: ReadonlyMap<string, FrozenToolBinding>;
}
interface FrozenToolBinding {
readonly offerId: string;
readonly hostPathAccess: ClientCapabilityOffer['hostPathAccess'];
readonly descriptor: ClientCapabilityToolDescriptor;
}
type SessionCapabilityBinding =
| { readonly kind: 'bound'; readonly providerId: string }
| { readonly kind: 'lost'; readonly providerId: string };
type SessionBindingMode = 'strict' | 'degrade';
interface SessionCapabilityState {
readonly initiatingProviderId?: string;
readonly serviceProviderId?: string;
readonly sessionBindings: ReadonlyMap<string, SessionCapabilityBinding>;
readonly turnBindings: ReadonlyMap<string, SessionCapabilityBinding>;
}
type SessionBindingSelection =
| {
readonly ok: true;
readonly state: SessionCapabilityState;
readonly modelToolsChanged: boolean;
}
| { readonly ok: false; readonly message: string };
type SessionBindingResult =
| { readonly ok: true }
| { readonly ok: false; readonly message: string };
export type SessionBindingPreview<T> =
| {
readonly ok: true;
readonly value: T;
commit(): Promise<SessionBindingResult>;
}
| { readonly ok: false; readonly message: string };
interface SelectedOfferBinding {
readonly registration: CapabilityRegistration;
readonly offer: FrozenOfferBinding;
}
interface SnapshotOfferBinding {
readonly offer: FrozenOfferBinding;
readonly registration?: CapabilityRegistration;
}
type ClientCapabilityBoundTool = ReturnType<McpToolProvider['toolSnapshot']>['tools'][number];
type ClientCapabilityToolBinding = ClientCapabilityBoundTool['binding'];
export interface HostClientCapabilityCoordinatorOptions {
readonly activation: RuntimePolicyActivationGate;
readonly onModelToolsChanged: () => void;
readonly interactions: Pick<HostInteractionCoordinator, 'requestClientCapabilityApproval'>;
readonly grants: Pick<
InteractiveInteractionStoreWriterFacade,
'readClientCapabilitySessionGrant'
>;
}
export interface ClientCapabilityServiceInvocationInput {
readonly connectionId: string;
readonly serviceId: string;
readonly version: string;
readonly method: string;
readonly input: Record<string, unknown>;
readonly signal?: AbortSignal;
readonly timeoutMs?: number;
}
export interface SessionClientCapabilityServiceInvocationInput
extends Omit<ClientCapabilityServiceInvocationInput, 'connectionId'> {
readonly sessionId: string;
}
/**
* Host-owned registry, selection authority, and reverse-call lifecycle for
* open-world Client Capability providers.
*/
export class HostClientCapabilityCoordinator implements ClientCapabilityService {
readonly handlers: ClientCapabilityOperationHandlerMap = {
'client.capability.replace': (input, context) => this.#replace(input, context),
'client.capability.unregister': (input, context) => this.#unregister(input, context),
};
readonly #activation: RuntimePolicyActivationGate;
readonly #onModelToolsChanged: () => void;
readonly #interactions: HostClientCapabilityCoordinatorOptions['interactions'];
readonly #grants: HostClientCapabilityCoordinatorOptions['grants'];
readonly #providers = new Map<string, ClientProviderState>();
readonly #connections = new Map<string, ClientProviderConnection>();
readonly #sessions = new Map<string, SessionCapabilityState>();
readonly #pendingApprovals = new Map<string, Promise<'allow' | 'deny'>>();
readonly #previewSessions = new AsyncLocalStorage<ReadonlyMap<string, SessionCapabilityState>>();
readonly #pendingConnectionReleases = new Set<Promise<void>>();
readonly #invocations: ClientCapabilityInvocationBroker<CapabilityRegistration>;
#revision = 0;
#draining = false;
constructor(options: HostClientCapabilityCoordinatorOptions) {
this.#activation = options.activation;
this.#onModelToolsChanged = options.onModelToolsChanged;
this.#interactions = options.interactions;
this.#grants = options.grants;
this.#invocations = new ClientCapabilityInvocationBroker({
senderFor: (connectionId) => {
const connection = this.#connections.get(connectionId);
return connection && this.#activeConnection(connection.provider) === connection
? connection.sender
: undefined;
},
onRegistrationIdle: (registration) => this.#releaseRegistrationIfUnused(registration),
});
}
attachConnection(
identity: ClientCapabilityConnectionIdentity,
sender: ClientCapabilityConnectionSender,
): ClientCapabilityConnection {
if (this.#draining) throw new Error('Client Capability registry is draining');
if (this.#connections.has(identity.connectionId)) {
throw new Error('Client Capability connection identity already exists');
}
const provider = this.#provider(identity);
this.#connections.set(identity.connectionId, {
connectionId: identity.connectionId,
provider,
sender,
superseded: false,
});
let closeTask: Promise<void> | undefined;
return {
accept: (frame) => {
if (closeTask) return;
this.#invocations.accept(identity.connectionId, frame);
},
close: () => {
closeTask ??= this.releaseConnection(identity.connectionId);
return closeTask;
},
};
}
async bindSession(
sessionId: string,
initiatingConnectionId: string,
): Promise<{ readonly ok: true } | { readonly ok: false; readonly message: string }> {
return this.#bindSession(sessionId, initiatingConnectionId, 'strict');
}
async bindSessionSuccessor(sessionId: string): Promise<void> {
const result = await this.#bindSession(sessionId, '', 'degrade');
if (!result.ok) {
throw new Error(`Session successor capability binding failed: ${result.message}`);
}
}
/** Rebuild Session-scoped capability bindings from a durable root contract. */
async bindDurableRoot(input: {
sessionId: string;
execution: RootExecutionDescriptor;
}): Promise<void> {
if (input.execution.kind !== 'external_message') return;
// A live root already selected its Client capabilities at admission. Only
// cold recovery needs to rebuild a missing in-memory binding from the
// durable root contract; reselecting here would discard the active
// connection/turn-affine binding and can make providers ambiguous.
if (this.#sessions.has(input.sessionId)) return;
await this.#activation.runMutation(async () => {
const selection = this.#selectSessionState(input.sessionId, '', 'degrade');
if (!selection.ok) throw new Error(selection.message);
this.#storeSessionState(input.sessionId, selection.state);
if (selection.modelToolsChanged) this.#onModelToolsChanged();
});
}
async #bindSession(
sessionId: string,
initiatingConnectionId: string,
mode: SessionBindingMode,
): Promise<SessionBindingResult> {
return this.#activation.runMutation(async () => {
const selection = this.#selectSessionState(sessionId, initiatingConnectionId, mode);
if (!selection.ok) return selection;
this.#storeSessionState(sessionId, selection.state);
if (selection.modelToolsChanged) this.#onModelToolsChanged();
return { ok: true };
});
}
async runWithSessionBindingPreview<T>(
sessionId: string,
initiatingConnectionId: string,
operation: () => Promise<T>,
): Promise<SessionBindingPreview<T>> {
return this.#activation.runReadActivation(async () => {
const registryRevision = this.#revision;
const selection = this.#selectSessionState(sessionId, initiatingConnectionId, 'strict');
if (!selection.ok) return selection;
const inherited = this.#previewSessions.getStore();
const preview = new Map(inherited ?? []);
preview.set(sessionId, selection.state);
return {
ok: true,
value: await this.#previewSessions.run(preview, operation),
commit: () =>
this.#commitSessionBindingPreview(
sessionId,
initiatingConnectionId,
registryRevision,
selection.state,
),
};
});
}
#commitSessionBindingPreview(
sessionId: string,
initiatingConnectionId: string,
registryRevision: number,
previewState: SessionCapabilityState,
): Promise<SessionBindingResult> {
return this.#activation.runMutation(async () => {
if (this.#revision !== registryRevision) {
return {
ok: false,
message: 'Client Capability registry changed after continuation safety preview',
};
}
const selection = this.#selectSessionState(sessionId, initiatingConnectionId, 'strict');
if (!selection.ok) return selection;
if (!sessionCapabilityStatesEqual(selection.state, previewState)) {
return {
ok: false,
message: 'Client Capability Session binding changed after continuation safety preview',
};
}
this.#storeSessionState(sessionId, selection.state);
if (selection.modelToolsChanged) this.#onModelToolsChanged();
return { ok: true };
});
}
#selectSessionState(
sessionId: string,
initiatingConnectionId: string,
mode: SessionBindingMode,
): SessionBindingSelection {
const initiatingProvider = this.#connections.get(initiatingConnectionId)?.provider;
const directProvider =
initiatingProvider?.current && this.#activeConnection(initiatingProvider)
? initiatingProvider
: undefined;
const associatedProviders =
initiatingProvider &&
initiatingProvider.credentialBoundClientInstanceId === initiatingProvider.clientInstanceId
? [...this.#providers.values()].filter(
(provider) =>
provider.trustedProvider &&
provider.current !== undefined &&
this.#activeConnection(provider) !== undefined &&
provider.capabilityOwner?.principalId === initiatingProvider.principalId &&
provider.capabilityOwner.clientInstanceId === initiatingProvider.clientInstanceId,
)
: [];
if (!directProvider && associatedProviders.length > 1) {
return {
ok: false,
message: 'Multiple Client Capability providers are bound to the initiating Client',
};
}
const selectedInitiatingProvider = directProvider ?? associatedProviders[0];
// A remote Client must never inherit an unrelated provider merely because
// it is the only candidate. Local-owner and recovery flows retain their
// existing provider-independent fallback when no provider was selected.
const initiatingProviderId =
selectedInitiatingProvider?.providerId ??
(initiatingProvider?.principalKind === 'remote_owner'
? initiatingProvider.providerId
: undefined);
const previousState = this.#sessions.get(sessionId);
const serviceProviderId =
previousState?.serviceProviderId ??
(selectedInitiatingProvider?.current &&
selectedInitiatingProvider.current.servicesByContract.size > 0
? initiatingProviderId
: undefined);
const previous = previousState?.sessionBindings ?? new Map();
const eligible = this.#eligibleOffersByContract();
const next = new Map<string, SessionCapabilityBinding>();
const selected: SelectedOfferBinding[] = [];
const sessionContractIds = new Set([
...previous.keys(),
...[...eligible]
.filter(([, candidates]) => candidates[0]?.offer.offer.affinity === 'session')
.map(([contractId]) => contractId),
]);
for (const contractId of [...sessionContractIds].sort()) {
const previousBinding = previous.get(contractId);
const candidates = eligible.get(contractId) ?? [];
let candidate: SelectedOfferBinding | undefined;
if (previousBinding?.kind === 'bound') {
candidate = candidates.find(
(entry) => entry.registration.providerId === previousBinding.providerId,
);
if (!candidate) {
if (mode === 'degrade') {
next.set(contractId, { kind: 'lost', providerId: previousBinding.providerId });
continue;
}
return {
ok: false,
message:
'A Session-bound Client Capability provider is no longer available for its frozen contract',
};
}
} else if (previousBinding?.kind === 'lost') {
candidate = candidates.find(
(entry) => entry.registration.providerId === previousBinding.providerId,
);
if (!candidate) {
if (mode === 'degrade') {
next.set(contractId, previousBinding);
continue;
}
return {
ok: false,
message: 'A Session-bound Client Capability provider has not reconnected',
};
}
} else {
candidate = selectProviderCandidate(candidates, initiatingProviderId);
if (!candidate && initiatingProviderId === undefined && candidates.length > 1) {
if (mode === 'degrade') continue;
return {
ok: false,
message:
'Multiple Client Capability providers offer the same contract and no initiating provider can be selected',
};
}
}
if (!candidate) continue;
next.set(contractId, {
kind: 'bound',
providerId: candidate.registration.providerId,
});
selected.push(candidate);
}
const proxyNames = new Map<string, string>();
for (const candidate of selected) {
if (offerConflictsWithProxyNames(candidate.offer, proxyNames)) {
if (mode === 'degrade') {
if (previous.has(candidate.offer.contractId)) {
next.set(candidate.offer.contractId, {
kind: 'lost',
providerId: candidate.registration.providerId,
});
} else {
next.delete(candidate.offer.contractId);
}
continue;
}
return {
ok: false,
message: 'Client Capability contracts expose conflicting model tool identities',
};
}
rememberOfferProxyNames(candidate.offer, proxyNames);
}
const previousTurn = previousState?.turnBindings ?? new Map();
const nextTurn = new Map<string, SessionCapabilityBinding>();
for (const [contractId, candidates] of [...eligible].sort(([left], [right]) =>
left.localeCompare(right),
)) {
if (candidates[0]?.offer.offer.affinity !== 'turn') continue;
const candidate = selectProviderCandidate(candidates, initiatingProviderId);
if (!candidate || offerConflictsWithProxyNames(candidate.offer, proxyNames)) continue;
nextTurn.set(contractId, {
kind: 'bound',
providerId: candidate.registration.providerId,
});
rememberOfferProxyNames(candidate.offer, proxyNames);
}
return {
ok: true,
state: {
...(initiatingProviderId ? { initiatingProviderId } : {}),
...(serviceProviderId ? { serviceProviderId } : {}),
sessionBindings: next,
turnBindings: nextTurn,
},
modelToolsChanged:
!bindingMapsEqual(previous, next) ||
!bindingMapsEqual(previousTurn, nextTurn) ||
(previousState?.initiatingProviderId !== initiatingProviderId &&
[...eligible.values()].some(
(candidates) => candidates[0]?.offer.offer.affinity === 'call',
)),
};
}
snapshotForSession(sessionId: string): ClientCapabilitySnapshot | undefined {
const state = this.#previewSessions.getStore()?.get(sessionId) ?? this.#sessions.get(sessionId);
const bindings = state?.sessionBindings;
const turnBindings = state?.turnBindings;
const selected: SnapshotOfferBinding[] = [];
const proxyNames = new Map<string, string>();
for (const [contractId, binding] of [...(bindings ?? [])].sort(([left], [right]) =>
left.localeCompare(right),
)) {
if (binding.kind === 'lost') continue;
const provider = this.#providers.get(binding.providerId);
const registration = provider?.current;
const offer = registration?.offersByContract.get(contractId);
if (!provider || !this.#activeConnection(provider) || !registration || !offer) {
throw new ClientCapabilityInvocationError(
'capability_lost',
'A Session-bound Client Capability provider is unavailable',
);
}
selected.push({ registration, offer });
rememberOfferProxyNames(offer, proxyNames);
}
for (const [contractId, binding] of [...(turnBindings ?? [])].sort(([left], [right]) =>
left.localeCompare(right),
)) {
const provider =
binding.kind === 'bound' ? this.#providers.get(binding.providerId) : undefined;
const registration = provider?.current;
const offer = registration?.offersByContract.get(contractId);
if (
!provider ||
!this.#activeConnection(provider) ||
!registration ||
!offer ||
offerConflictsWithProxyNames(offer, proxyNames)
) {
continue;
}
selected.push({ registration, offer });
rememberOfferProxyNames(offer, proxyNames);
}
const eligible = this.#eligibleOffersByContract();
for (const [contractId, candidates] of [...eligible].sort(([left], [right]) =>
left.localeCompare(right),
)) {
// A provider-independent snapshot keeps one representative descriptor so
// a dynamic call can report ambiguity. A remote Client's explicit
// selector must instead hide every unrelated provider.
const offer =
state?.initiatingProviderId === undefined
? candidates[0]?.offer
: selectProviderCandidate(candidates, state.initiatingProviderId)?.offer;
if (
!offer ||
offer.offer.affinity !== 'call' ||
offerConflictsWithProxyNames(offer, proxyNames)
) {
continue;
}
selected.push({ offer });
rememberOfferProxyNames(offer, proxyNames);
}
if (selected.length === 0) return;
const trusted = selected.filter((binding) => binding.registration?.trustedProvider === true);
const interactive = selected.filter(
(binding) => binding.registration?.trustedProvider !== true,
);
assertUniqueSnapshotToolIdentities(selected);
const tools = [
...buildMcpTools(this.#snapshotProvider(state?.initiatingProviderId, interactive), {
callTimeoutMs: DEFAULT_CALL_TIMEOUT_MS,
categoryHint: 'client_capability',
hostAdmission: 'client_capability',
recoveryMode: 'outcome_unknown',
executionLocation: 'remote',
}),
...buildMcpTools(this.#snapshotProvider(state?.initiatingProviderId, trusted), {
callTimeoutMs: DEFAULT_CALL_TIMEOUT_MS,
categoryHint: 'custom_tool',
hostAdmission: 'client_capability',
recoveryMode: 'outcome_unknown',
executionLocation: 'remote',
activityKindForDescriptor: (descriptor) => trustedClientToolActivityKind(descriptor),
}),
];
const groups = selected.map(({ offer: binding }) => ({
id: binding.contractId,
toolNames: binding.offer.tools.map((tool) => mcpProxyToolName(tool.serverId, tool.name)),
label: binding.offer.label,
...(binding.offer.description ? { description: binding.offer.description } : {}),
}));
const registrations = [
...new Set(selected.flatMap(({ registration }) => (registration ? [registration] : []))),
];
for (const registration of registrations) registration.snapshotRefs += 1;
let released = false;
return Object.freeze({
registrationIds: Object.freeze(
registrations.map((registration) => registration.registrationId),
),
groups: Object.freeze(groups),
tools: Object.freeze(tools),
release: () => {
if (released) return;
released = true;
for (const registration of registrations) {
if (registration.snapshotRefs === 0) {
throw new Error('Client Capability snapshot residency underflow');
}
registration.snapshotRefs -= 1;
this.#releaseRegistrationIfUnused(registration);
}
},
});
}
async callService(
input: ClientCapabilityServiceInvocationInput,
): Promise<Record<string, unknown>> {
const connection = this.#connections.get(input.connectionId);
const provider = connection?.provider;
const registration = provider?.current;
const service = registration?.servicesByContract.get(
serviceContract(input.serviceId, input.version),
);
if (
!connection ||
!provider ||
this.#activeConnection(provider) !== connection ||
!registration ||
!service
) {
throw new ClientCapabilityInvocationError(
'capability_lost',
'Client Capability service is unavailable on the initiating connection',
);
}
const result = await this.#invocations.invokeService(
registration,
service.serviceId,
service.version,
input.method,
input.input,
input.signal,
input.timeoutMs ?? DEFAULT_CALL_TIMEOUT_MS,
);
if (
result.content.length !== 0 ||
!result.structuredContent ||
typeof result.structuredContent !== 'object' ||
Array.isArray(result.structuredContent)
) {
throw new ClientCapabilityInvocationError(
'provider_failed',
'Client Capability service returned an invalid payload',
);
}
return result.structuredContent as Record<string, unknown>;
}
async callServiceForSession(
input: SessionClientCapabilityServiceInvocationInput,
): Promise<Record<string, unknown>> {
const state =
this.#previewSessions.getStore()?.get(input.sessionId) ?? this.#sessions.get(input.sessionId);
const preferred = state?.serviceProviderId;
const candidates = [...this.#providers.values()].filter((provider) => {
const connection = this.#activeConnection(provider);
return Boolean(
connection &&
provider.current?.servicesByContract.has(serviceContract(input.serviceId, input.version)),
);
});
const provider = preferred
? candidates.find((candidate) => candidate.providerId === preferred)
: candidates.length === 1
? candidates[0]
: undefined;
const connection = provider ? this.#activeConnection(provider) : undefined;
if (!connection) {
throw new ClientCapabilityInvocationError(
!preferred && candidates.length > 1 ? 'capability_ambiguous' : 'capability_lost',
!preferred && candidates.length > 1
? 'Multiple Client Capability providers offer this service'
: 'The initiating Client Capability service is unavailable for this Session',
);
}
return this.callService({
connectionId: connection.connectionId,
serviceId: input.serviceId,
version: input.version,
method: input.method,
input: input.input,
...(input.signal ? { signal: input.signal } : {}),
...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
});
}
async callWorkspaceService(
input: Omit<ClientCapabilityServiceInvocationInput, 'connectionId'>,
): Promise<Record<string, unknown>> {
const candidates = [...this.#providers.values()]
.filter((provider) => {
const connection = this.#activeConnection(provider);
return Boolean(
connection &&
provider.current?.servicesByContract.has(
serviceContract(input.serviceId, input.version),
),
);
})
.sort((left, right) => left.providerId.localeCompare(right.providerId));
const provider = candidates[0];
const connection = provider ? this.#activeConnection(provider) : undefined;
if (!connection) {
throw new ClientCapabilityInvocationError(
'capability_lost',
'No Client Capability provider offers this workspace service',
);
}
return this.callService({
connectionId: connection.connectionId,
serviceId: input.serviceId,
version: input.version,
method: input.method,
input: input.input,
...(input.signal ? { signal: input.signal } : {}),
...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
});
}
hasWorkspaceService(serviceId: string, version: string): boolean {
return [...this.#providers.values()].some((provider) => {
const connection = this.#activeConnection(provider);
return Boolean(
connection && provider.current?.servicesByContract.has(serviceContract(serviceId, version)),
);
});
}
hasService(connectionId: string, serviceId: string, version: string): boolean {
const connection = this.#connections.get(connectionId);
const provider = connection?.provider;
return Boolean(
connection &&
provider &&
this.#activeConnection(provider) === connection &&
provider.current?.servicesByContract.has(serviceContract(serviceId, version)),
);
}
retireSessions(sessionIds: readonly string[]): void {
for (const sessionId of new Set(sessionIds)) this.#sessions.delete(sessionId);
for (const provider of this.#providers.values()) this.#deleteProviderIfUnused(provider);
}
releaseConnection(connectionId: string): Promise<void> {
const invocationCleanup = this.#invocations.releaseConnection(connectionId);
const connection = this.#connections.get(connectionId);
if (!connection) return invocationCleanup;
let task!: Promise<void>;
task = Promise.all([
invocationCleanup,
this.#activation.runMutation(() => this.#releaseConnectionState(connection)),
])
.then(() => undefined)
.finally(() => this.#pendingConnectionReleases.delete(task));
this.#pendingConnectionReleases.add(task);
void task.catch(() => undefined);
return task;
}
#releaseConnectionState(connection: ClientProviderConnection): void {
if (this.#connections.get(connection.connectionId) !== connection) return;
const { provider } = connection;
this.#connections.delete(connection.connectionId);
if (provider.activeConnectionId !== connection.connectionId) {
this.#deleteProviderIfUnused(provider);
return;
}
provider.activeConnectionId = undefined;
if (provider.current) {
const registration = provider.current;
provider.current = undefined;
this.#markBindingsLost(provider.providerId);
this.#removeTurnBindings(provider.providerId);
this.#revision += 1;
if (hasModelToolOffers(registration)) this.#onModelToolsChanged();
}
for (const registration of [...provider.registrations.values()]) {
this.#releaseRegistrationIfUnused(registration);
}
this.#deleteProviderIfUnused(provider);
this.#pruneEmptySessions();
}
beginDrain(): void {
this.#draining = true;
}
async close(): Promise<void> {
this.beginDrain();
const releases = [...this.#connections.keys()].map((connectionId) =>
this.releaseConnection(connectionId),
);
await Promise.allSettled(releases);
await Promise.allSettled([...this.#pendingConnectionReleases]);
this.#invocations.close();
this.#sessions.clear();
}
#replace(
input: ClientCapabilityReplaceInput,
context: ConnectionContext,
): ReturnType<ClientCapabilityOperationHandlerMap['client.capability.replace']> {
return this.#activation.runMutation(async () => {
if (this.#draining) {
return {
ok: false,
error: {
code: 'host_draining',
message: 'Client Capability registry is draining',
},
};
}
const connection = this.#connections.get(context.connectionId);
if (!connection) {
return {
ok: false,
error: {
code: 'operation_unavailable',
message: 'Client Capability reverse-call channel is unavailable',
},
};
}
const { provider } = connection;
if (connection.superseded) {
return {
ok: false,
error: {
code: 'invalid_request',
message: 'Client Capability connection has been superseded',
},
};
}
if (provider.registrations.has(input.registrationId)) {
return {
ok: false,
error: {
code: 'invalid_request',
message: 'Client Capability registration identity already exists',
},
};
}
let registration: CapabilityRegistration;
try {
if (
provider.principalKind === 'capability_provider' &&
(input.services?.length ||
input.offers.some(
(offer) => offer.affinity !== 'session' || offer.hostPathAccess !== 'none',
))
) {
throw new Error(
'A trusted capability provider may publish only path-independent session capabilities',
);
}
registration = freezeRegistration(
provider.providerId,
context.connectionId,
input,
provider.trustedProvider,
);
} catch (error) {
return {
ok: false,
error: {
code: 'invalid_request',
message: asError(error).message,
},
};
}
const previous = provider.current;
const previousConnectionId = provider.activeConnectionId;
if (previousConnectionId && previousConnectionId !== context.connectionId) {
const previousConnection = this.#connections.get(previousConnectionId);
if (previousConnection) previousConnection.superseded = true;
this.#invocations.releaseConnection(previousConnectionId);
}
provider.activeConnectionId = context.connectionId;
provider.current = registration;
const currentContracts = new Set(registration.offersByContract.keys());
if (previous) {
this.#retireBindings(
provider.providerId,
new Set(
[...previous.offersByContract.keys()].filter(
(contractId) => !currentContracts.has(contractId),
),
),
);
this.#removeTurnBindings(
provider.providerId,
new Set(
[...previous.offersByContract.keys()].filter(
(contractId) => !currentContracts.has(contractId),
),
),
);
}
this.#restoreBindings(provider.providerId, currentContracts);
provider.registrations.set(registration.registrationId, registration);
this.#revision += 1;
if (hasModelToolOffers(previous) || hasModelToolOffers(registration)) {
this.#onModelToolsChanged();
}
if (previous) this.#releaseRegistrationIfUnused(previous);
this.#pruneEmptySessions();
return {
ok: true,
result: {
registrationId: registration.registrationId,
revision: this.#revision,
},
};
});
}
#unregister(
input: ClientCapabilityUnregisterInput,
context: ConnectionContext,
): ReturnType<ClientCapabilityOperationHandlerMap['client.capability.unregister']> {
return this.#activation.runMutation(async () => {
const provider = this.#connections.get(context.connectionId)?.provider;
if (
provider?.activeConnectionId !== context.connectionId ||
!provider.current ||
provider.current.registrationId !== input.registrationId
) {
return {
ok: false,
error: {
code: 'invalid_request',
message: 'Client Capability registration is not current',
},
};
}
const registration = provider.current;
provider.current = undefined;
this.#retireBindings(provider.providerId, new Set(registration.offersByContract.keys()));
this.#removeTurnBindings(provider.providerId, new Set(registration.offersByContract.keys()));
this.#revision += 1;
if (hasModelToolOffers(registration)) this.#onModelToolsChanged();
this.#releaseRegistrationIfUnused(registration);
this.#pruneEmptySessions();
return {
ok: true,
result: {
registrationId: registration.registrationId,
revision: this.#revision,
},
};
});
}
#snapshotProvider(
initiatingProviderId: string | undefined,
selected: readonly SnapshotOfferBinding[],
): McpToolProvider {