Repository navigation
Expand file tree
/
Copy pathindex.bs
More file actions
1822 lines (1344 loc) · 77.7 KB
/
Copy pathindex.bs
File metadata and controls
1822 lines (1344 loc) · 77.7 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
<pre class='metadata'>
Title: WebMCP
Shortname: webmcp
Level: None
Status: CG-DRAFT
Group: webml
Repository: webmachinelearning/webmcp
URL: https://webmachinelearning.github.io/webmcp
Editor: Brandon Walderman, Microsoft https://www.microsoft.com, [email protected], w3cid 115877
Editor: Khushal Sagar, Google https://www.google.com, [email protected], w3cid 122787
Editor: Dominic Farolino, Google https://www.google.com, [email protected], w3cid 102763
Abstract: The WebMCP API enables web applications to provide JavaScript-based tools to AI agents.
Markup Shorthands: markdown yes, css no
Complain About: accidental-2119 yes, missing-example-ids yes
Assume Explicit For: yes
Default Biblio Status: current
Boilerplate: omit conformance
Indent: 2
Die On: warning
Test Suite: https://wpt.fyi/results/webmcp
</pre>
<style>
/* domintro and XXX from https://resources.whatwg.org/standard.css */
.domintro {
position: relative;
color: green;
background: #DDFFDD;
margin: 2.5em 0 2em 0;
padding: 1.5em 1em 0.5em 2em;
}
.domintro dt, .domintro dt * {
color: black;
font-size: inherit;
}
.domintro dd {
margin: 0.5em 0 1em 2em; padding: 0;
}
.domintro dd p {
margin: 0.5em 0;
}
.domintro::before {
content: 'For web developers (non-normative)';
background: green;
color: white;
padding: 0.15em 0.25em;
font-style: normal;
position: absolute;
top: -0.8em;
left: -0.8em;
}
.XXX {
color: #D50606;
/* The value #111 is what WHATWG uses in dark mode: `--xxx-bg: #111;`. */
background: light-dark(white, #111);
border: solid #D50606;
}
/* dl.props from https://resources.whatwg.org/standard.css */
dl.props { display: grid; grid-template-columns: max-content auto; row-gap: 0.25em; column-gap: 1em; }
dl.props > dt { grid-column-start: 1; margin: 0; }
dl.props > dd { grid-column-start: 2; margin: 0; }
p + dl.props { margin-top: -0.5em; }
/* Put nice boxes around each algorithm. */
[data-algorithm]:not(.heading) {
padding: .5em;
border: thin solid #ddd; border-radius: .5em;
margin: .5em calc(-0.5em - 1px);
}
[data-algorithm]:not(.heading) > :first-child {
margin-top: 0;
}
[data-algorithm]:not(.heading) > :last-child {
margin-bottom: 0;
}
[data-algorithm] [data-algorithm] {
margin: 1em 0;
}
/* Table styling definitions from https://resources.whatwg.org/standard.css */
table { border-collapse: collapse; border-style: hidden hidden none hidden; margin: 1.25em 0; }
table thead, table tbody { border-bottom: solid; }
table tbody th { text-align: left; }
table tbody th:first-child { border-left: solid; }
table td, table th { border-left: solid; border-right: solid; border-bottom: solid thin; vertical-align: top; padding: 0.2em; }
</style>
<pre class="link-defaults">
spec:html; type:dfn;
text:form-associated element
text:browsing context group set
text:unique internal value
text:is origin-keyed
spec: webidl; type: dfn;
text: an exception was thrown
</pre>
<pre class="anchors">
spec: html; urlPrefix: https://html.spec.whatwg.org/C
type: dfn
text: browsing context group
spec: SECURE-CONTEXTS; urlPrefix: https://w3c.github.io/webappsec-secure-contexts/
type: abstract-op
text: is origin potentially trustworthy?; url: is-origin-trustworthy
spec: ECMASCRIPT; urlPrefix: https://tc39.es/ecma262/
type: dfn
text: surrounding agent; url: surrounding-agent
text: agent cluster; url: sec-agent-clusters
</pre>
<h2 id="intro">Introduction</h2>
WebMCP API is a new JavaScript interface that allows web developers to expose their web application functionality as “tools” - JavaScript functions with natural language descriptions and structured schemas that can be invoked by [=agents=], [=browser's agents=], and [=assistive technologies=]. Web pages that use WebMCP can be thought of as Model Context Protocol [[!MCP]] servers that implement tools in client-side script instead of on the backend. WebMCP enables collaborative workflows where users and agents work together within the same web interface, leveraging existing application logic while maintaining shared context and user control.
<h2 id="terminology">Terminology</h2>
<!--
TODO: Define any reusable high-level terms here that are not specific to algorithms and not defined elsewhere (https://respec.org/xref/), consider exporting (https://speced.github.io/bikeshed/#dfn-export) if useful for other specs
-->
An <dfn>agent</dfn> is an autonomous assistant that can understand a user’s goals and take actions on the user’s behalf to achieve them. Today, these are typically implemented by large language model (LLM) based [=AI platforms=], interacting with users via text-based chat interfaces.
A <dfn>browser’s agent</dfn> is an [=agent=] provided by or through the browser that could be built directly into the browser or hosted by it, for example, via an extension or plug-in.
An <dfn>AI platform</dfn> is a provider of agentic assistants such as OpenAI’s ChatGPT, Anthropic’s Claude, or Google’s Gemini.
<h2 id="supporting-concepts">Supporting concepts</h2>
A <dfn>model context</dfn> is a [=struct=] with the following [=struct/items=]:
<dl dfn-for="model context">
: <dfn>tool map</dfn>
:: a [=map=] whose [=map/keys=] are [=strings=] and whose [=map/values=] are [=tool definition=]
[=structs=].
: <dfn>local pending tool executions map</dfn>
:: a [=map=] whose [=map/keys=] are [=unique internal values=] and whose [=map/values=] are
[=local pending tool execution=] [=structs=]. It is initially empty.
Note: this map is similar to a [=traversable navigable=]'s [=traversable navigable/pending tool
executions map=], but it only contains pending execution information for tools under a single
{{ModelContext}} object. It is used to store objects that can only be accessed from that
object's event loop, and because it is event-loop-local, it can get out of sync from the
[=traversable navigable=]'s more "global" map.
</dl>
A <dfn>tool definition</dfn> is a [=struct=] with the following [=struct/items=]:
<dl dfn-for="tool definition">
: <dfn>name</dfn>
:: a [=string=] uniquely identifying a tool registered within a [=model context=]'s [=model
context/tool map=]; it is the same as the [=map/key=] identifying this object.
The [=tool definition/name=]'s [=string/length=] must be between 1 and 128, inclusive, and only
consist of [=ASCII alphanumeric=] [=code points=], U+005F LOW LINE (_),
U+002D HYPHEN-MINUS (-), and U+002E FULL STOP (.).
: <dfn>title</dfn>
:: A [=string=]-or-null representing a human-readable title of the tool for use in user interfaces.
Note: If {{ModelContextTool/title}} is not provided, the user agent is free to use a different
value for display.
: <dfn>description</dfn>
:: a [=string=].
: <dfn>input schema</dfn>
:: a [=string=].
Note: For tools registered by the imperative form of this API (i.e.,
{{ModelContext/registerTool()}}), this is the stringified representation of
{{ModelContextTool/inputSchema}}. For tools registered
[declaratively](https://github.com/webmachinelearning/webmcp/blob/main/declarative-api-explainer.md), this will be a
stringified JSON Schema object created by the
[=synthesize a declarative JSON Schema object algorithm=].
[[!JSON-SCHEMA]]
: <dfn>execute steps</dfn>
:: an algorithm that takes a {{Document}} <var ignore>targetDocument</var>, a [=string=] <var
ignore>inputArguments</var>, an algorithm <var ignore>completionSteps</var> that takes a
[=string=]-or-null and a [=boolean=], and a [=unique internal value=] <var ignore>uuid</var>.
Note: For tools registered imperatively, these steps will simply invoke the [=imperative
execute steps=]. For tools registered
[declaratively](https://github.com/webmachinelearning/webmcp/blob/main/declarative-api-explainer.md), this will be a set of
"internal" steps that have not been defined yet, that describe how to fill out a <{form}> and
its [=form-associated elements=].
: <dfn>annotations</dfn>
:: an [=annotations=]-or-null.
: <dfn>exposed origins</dfn>
:: a [=list=] or [=origins=], initially [=list/empty=].
</dl>
A <dfn>local pending tool execution</dfn> is a [=struct=] with the following [=struct/items=]:
<dl dfn-for="local pending tool execution">
: <dfn>abort controller</dfn>
:: an {{AbortController}}.
</dl>
An <dfn>annotations</dfn> is a [=struct=] with the following [=struct/items=]:
<dl dfn-for="annotations">
: <dfn>read-only hint</dfn>
:: a [=boolean=], initially false.
: <dfn>untrusted content hint</dfn>
:: a [=boolean=], initially false.
</dl>
<h3 id="pending-tool-executions">Pending tool executions</h3>
A <dfn>pending tool execution</dfn> is a [=struct=] with the following [=struct/items=]:
<dl dfn-for="pending tool execution">
: <dfn>caller document</dfn>
:: a {{Document}}.
: <dfn>target document</dfn>
:: a {{Document}}.
: <dfn>tool name</dfn>
:: a [=string=].
: <dfn>completion steps</dfn>
:: an algorithm that takes a [=string=]-or-null and a [=boolean=].
</dl>
A [=traversable navigable=] has a <dfn for="traversable navigable">pending tool executions
map</dfn>, which is a [=map=] whose keys are [=unique internal values=] and whose values are
[=pending tool execution=] [=structs=]. It is initially empty.
Note: This map is only ever mutated from steps [=in parallel=]. This simulates the single,
authoritative "browser process" that most modern browsers implement, where execution tracking sits
outside any individual Document process's event loop, and is accessed asynchronously via some
inter-process communication mechanism.
<div algorithm>
To <dfn>cancel a pending tool execution</dfn> given a [=traversable navigable=] |traversable| and a
[=unique internal value=] |uuid|:
1. [=Assert=]: these steps are running [=in parallel=].
1. If |traversable|'s [=traversable navigable/pending tool executions map=][|uuid|] does not
[=map/exist=], then return.
Note: See <a href=#pending-execution-removal-race>this note</a> to learn how a tool's natural
resolution/rejection can race with the caller's cancellation. This might result in the pending
execution entry for |uuid| being removed before we get here. In that case, the
{{ModelContext/executeTool()}} promise will still be rejected with the abort
[=AbortSignal/abort reason=], and will never observe the tool's natural resolution/rejection.
1. Let |execution| be |traversable|'s [=traversable navigable/pending tool executions map=][|uuid|].
1. [=map/Remove=] |traversable|'s [=traversable navigable/pending tool executions map=][|uuid|].
1. Let |targetDocument| be |execution|'s [=pending tool execution/target document=].
Note: |targetDocument| is guaranteed to still exist (i.e., not be unloaded or destroyed) when
these steps run, because if |targetDocument| had been destroyed, then <a
href=#target-destroyed-cleanup>this specification's unloading document cleanup steps</a> would
have already removed |execution| from the map, and we'd have ended up in the early return path
above.
1. [=Queue a global task=] on the [=webmcp task source=] given |targetDocument|'s [=relevant global
object=] to run the following steps:
1. Let |localExecutions| be |targetDocument|'s [=Document/associated ModelContext|associated
<code>ModelContext</code>=]'s [=ModelContext/internal context=]'s [=model context/local
pending tool executions map=].
1. If |localExecutions|[|uuid|] does not [=map/exist=], then return.
1. Let |localExecution| be |localExecutions|[|uuid|].
1. [=map/Remove=] |localExecutions|[|uuid|].
1. [=AbortController/signal abort|Signal abort=] on |localExecution|'s [=local pending tool
execution/abort controller=].
Issue(#146): Fire the "toolcanceled" event at |targetDocument|'s relevant global object.
</div>
<hr>
<div algorithm=unloading-document-cleanup-steps>
This specification's [=unloading document cleanup steps=], given a {{Document}} |document|, are as
follows:
1. Let |traversable| be |document|'s [=node navigable=]'s [=navigable/traversable navigable=].
1. Run the following steps [=in parallel=]:
1. Let |executionsToRemove| be an empty [=list=].
1. [=map/For each=] |uuid| → |execution| of |traversable|'s [=traversable navigable/pending
tool executions map=]:
1. If |document| is |execution|'s [=pending tool execution/target document=] or |document| is
|execution|'s [=pending tool execution/caller document=], then [=list/append=] |uuid| to
|executionsToRemove|.
1. [=list/For each=] |uuid| of |executionsToRemove|:
1. Let |execution| be |traversable|'s [=traversable navigable/pending tool executions
map=][|uuid|].
1. <p id=target-destroyed-cleanup>If |document| is |execution|'s [=pending tool
execution/target document=] and is not |execution|'s [=pending tool execution/caller
document=], then run |execution|'s [=pending tool execution/completion steps=] given null
and false.</p>
Note: This removes |execution| from the [=traversable navigable/pending tool executions
map=].
1. <p id=caller-destroyed-cleanup>Otherwise, if |document| is |execution|'s [=pending tool
execution/caller document=] and is not |execution|'s [=pending tool execution/target
document=], then [=cancel a pending tool execution=] given |traversable| and |uuid|.</p>
1. Otherwise, [=map/Remove=] |traversable|'s [=traversable navigable/pending tool executions
map=][|uuid|].
1. [=Assert=]: |traversable|'s [=traversable navigable/pending tool executions map=][|uuid|]
does not [=map/exist=].
</div>
<hr>
<div algorithm>
To <dfn>notify documents of a tool change</dfn> given a {{Document}} |tool owner| and a [=list=] of
[=origins=] |exposed origins|, run these steps:
1. [=Assert=]: these steps are running [=in parallel=].
1. Let |navigablesToNotify| be |tool owner|'s [=node navigable=]'s [=navigable/traversable
navigable=]'s [=Document/inclusive descendant navigables=].
1. [=list/For each=] |navigable| of |navigablesToNotify|:
1. Let |targetDocument| be |navigable|'s [=navigable/active document=].
1. If |targetDocument| is not [=allowed to use=] the "{{tools}}" feature, then
[=iteration/continue=].
1. If [=tool is exposed to an origin=] given |tool owner|'s [=Document/origin=], |exposed
origins|, and |targetDocument|'s [=Document/origin=], then [=queue a global task=] on the
[=webmcp task source=] given |targetDocument|'s [=relevant global object=] to [=fire an
event=] named {{ModelContext/toolchange}} at |targetDocument|'s [=Document/associated
ModelContext|associated <code>ModelContext</code>=].
<div class=example id=notify-task-ordering>
<p>This algorithm's use of the [=webmcp task source=], and the fact that it runs [=in parallel=],
means that the timing between firing the {{ModelContext/toolchange}} event, and other tasks queued
after this algorithm, cannot be relied upon. For example:</p>
<xmp class=language-js>
document.modelContext.ontoolchange = e => console.log('Parent toolchange');
iframe.contentDocument.modelContext.ontoolchange = e => console.log('Child toolchange');
// Queues a task to fire `toolchange`, on the `webmcp task source`.
const p = document.modelContext.registerTool({
name: "tool_name",
description: "tool_desc",
execute: async () => {}
});
p.then(() => console.log('Register promise resolved'));
// Queues a task on the `timer task source`.
setTimeout(() => console.log('Post-register task'));
// `Parent toolchange` will always log before `Child toolchange`, and
// `Register promise resolved` will always log after both.
// But `Post-register task` can log before, in between, or after all three.
</xmp>
</div>
</div>
<div algorithm>
To determine if a <dfn>tool is exposed to an origin</dfn> given an [=origin=] |tool owner origin|,
a [=list=] of [=origins=] |exposed origins|, and an [=origin=] |accessing origin|, run these steps:
1. If |tool owner origin| is [=same origin=] with |accessing origin|, then return true.
1. [=list/For each=] |allowed origin| of |exposed origins|:
1. If |accessing origin| is [=same origin=] with |allowed origin|, then return true.
1. Return false.
</div>
<div algorithm>
The <dfn>tool execute steps</dfn>, given a [=string=] |toolName|, a {{Document}} |targetDocument|, a
[=string=] |inputArguments|, an algorithm |completionSteps|, and a [=unique internal value=] |uuid|,
are as follows. The |completionSteps| algorithm takes a [=string=]-or-null <var ignore>result</var>
and a [=boolean=] <var ignore>success</var>.
1. [=Assert=]: these steps are running on |targetDocument|'s [=relevant agent=]'s [=agent/event
loop=].
1. Let |toolMap| be |targetDocument|'s [=Document/associated ModelContext|associated
<code>ModelContext</code>=]'s [=ModelContext/internal context=]'s [=model context/tool map=].
1. If |toolMap|[|toolName|] does not [=map/exist=], then run |completionSteps| given null and false,
and abort these steps.
Issue: Support the plumbing of more granular errors back to the invoker; this should result in a
"{{NotFoundError}}" in the calling document.
<div class=note>
<p>This protects us against a race between tool unregistration and execution. While tool
<em>existence</em> is protected from this race, tool unregistration followed by a quick
re-registration of a tool with the same |toolName| but input schema is <em>not</em> protected
against.</p>
<p>This might result in |inputArguments| for an old tool being applied to the [=tool
definition/input schema=] of a newer tool, and causing whatever error that might cause, when <a
href=https://github.com/webmachinelearning/webmcp/issues/92>issue #92</a> is resolved.</p>
<div class=example id=unregistration-execution-race>
<xmp class=language-js>
// -- Tool owner document. --
const oldInputSchema = {...};
const newInputSchema = {...};
const ac = new AbortController();
document.modelContext.registerTool({..., inputSchema: oldInputSchema}, {signal: ac.signal});
// Unregister, and quickly re-register with an updated input schema.
ac.abort();
document.modelContext.registerTool({..., inputSchema: newInputSchema});
// -- Executing document. --
//
// This could target either the "old" tool, or the "new" one above,
// and the execution might encounter any requisite errors due to the mismatch.
const [tool] = await document.modelContext.getTools();
document.modelContext.executeTool(tool, {a: 10});
</xmp>
</div>
</div>
1. Let |tool| be |toolMap|[|toolName|].
1. Run |tool|'s [=tool definition/execute steps=] given |targetDocument|, |inputArguments|,
|completionSteps|, and |uuid|.
Note: This is the point where we branch into either the [=imperative execute steps=] or the
[=declarative execute steps=].
</div>
<div algorithm>
The <dfn>imperative execute steps</dfn>, given a {{ModelContextTool}} |tool|, a {{Document}}
|targetDocument|, a [=string=] |inputArguments|, an algorithm |completionSteps|, and a [=unique
internal value=] |uuid|, are as follows:
1. [=Assert=]: these steps are running on |targetDocument|'s [=relevant agent=]'s [=agent/event
loop=].
1. Let |inputObject| be the result of [=parse a JSON string to a JavaScript value=] given
|inputArguments| and |targetDocument|'s [=relevant realm=]. If <a lt="an exception was
thrown">exception was thrown</a>, then run |completionSteps| given null and false, and abort
these steps.
Issue: Support more granular errors; here we should return something that prompts the caller to
reject its {{Promise}} with a "{{DataError}}" {{DOMException}}.
1. If |inputObject| [=Object type|is not an Object=] is false, then run |completionSteps| given null
and false, and abort these steps.
Issue(#146): Specify and fire the "<code>toolactivated</code>" event.
1. Let |controller| be a [=new=] {{AbortController}} created in |targetDocument|'s [=relevant
realm=].
1. Let |localExecution| be a new [=local pending tool execution=] with the following [=struct/items=]:
: [=local pending tool execution/abort controller=]
:: |controller|
1. Set |targetDocument|'s [=Document/associated ModelContext|associated
<code>ModelContext</code>=]'s [=ModelContext/internal context=]'s [=model context/local pending
tool executions map=][|uuid|] to |localExecution|.
1. Let |options| be a new {{ToolExecuteCallbackOptions}} dictionary, with the following fields:
: {{ToolExecuteCallbackOptions/signal}}
:: |controller|'s [=AbortController/signal=]
1. Let |toolPromise| be the result of [=invoke|invoking=] |tool|'s {{ModelContextTool/execute}} with
|inputObject| and |options|.
1. [=promise/React=] to |toolPromise|:
- If |toolPromise| was fulfilled with value |v|:
1. Let |localExecutions| be |targetDocument|'s [=Document/associated ModelContext|associated
<code>ModelContext</code>=]'s [=ModelContext/internal context=]'s [=model context/local
pending tool executions map=].
1. If |localExecutions|[|uuid|] does not [=map/exist=], then return.
Note: The entry corresponding to |uuid| will not exist if the execution was [=cancel a
pending tool execution|cancelled=] (and thus the corresponding entry was removed) before
the developer's |toolPromise| settles.
1. [=map/Remove=] |localExecutions|[|uuid|].
1. Let |serializedResult| be the result of [=serializing a JavaScript value to a JSON
string=] given |v|. If this throws an exception, run |completionSteps| given null and
false, and abort these steps.
1. Run |completionSteps| given |serializedResult| and true.
- If |toolPromise| was rejected with reason |r|, then:
1. Optionally [=report a warning to the console=] describing |r|.
1. Let |localExecutions| be |targetDocument|'s [=Document/associated ModelContext|associated
<code>ModelContext</code>=]'s [=ModelContext/internal context=]'s [=model context/local
pending tool executions map=].
1. If |localExecutions|[|uuid|] does not [=map/exist=], then return.
1. [=map/Remove=] |localExecutions|[|uuid|].
1. Run |completionSteps| given null and false.
</div>
<div algorithm>
To <dfn for="model context">unregister a tool</dfn> given a {{ModelContext}} |modelContext| and a
[=string=] |tool name|, run these steps:
1. [=Assert=]: these steps are running on |modelContext|'s [=relevant agent=]'s [=agent/event
loop=].
1. Let |tool map| be |modelContext|'s [=ModelContext/internal context=]'s [=model context/tool
map=].
1. If |tool map|[|tool name|] does not [=map/exist=], then return.
1. Let |exposed origins| be |tool map|[|tool name|]'s [=tool definition/exposed origins=].
1. [=map/Remove=] |tool map|[|tool name|].
1. Let |targetDocument| be |modelContext|'s [=relevant global object=]'s [=associated
Document|associated <code>Document</code>=].
1. [=In parallel=], [=notify documents of a tool change=] given |targetDocument| and |exposed
origins|.
</div>
<h2 id="api">API</h2>
<!--
TODO: Sketch initial algorithms, define attributes and methods etc.
https://github.com/webmachinelearning/webmcp/blob/main/docs/proposal.md#api
https://dlaliberte.github.io/bikeshed-intro/#a-strategy-for-incremental-development
-->
<h3 id="document-extension">Extensions to {{Document}}</h3>
Each {{Document}} object has an <dfn for=Document>associated {{ModelContext}}</dfn>, which is a
{{ModelContext}} object.
Upon creation of the {{Document}} object, its [=Document/associated ModelContext|associated
<code>ModelContext</code>=] must be set to a [=new=] {{ModelContext}} object created in the
{{Document}}'s [=relevant realm=].
<hr>
<xmp class="idl">
partial interface Document {
[SecureContext, SameObject] readonly attribute ModelContext modelContext;
};
</xmp>
<div algorithm>
The <dfn attribute for=Document>modelContext</dfn> getter steps are:
1. Return [=this=]'s [=Document/associated ModelContext|associated <code>ModelContext</code>=]
object.
</div>
<h3 id="model-context-container">ModelContext Interface</h3>
The {{ModelContext}} interface provides methods for web applications to register and manage tools that can be invoked by [=agents=].
<xmp class="idl">
[Exposed=Window, SecureContext]
interface ModelContext : EventTarget {
Promise<undefined> registerTool(ModelContextTool tool, optional ModelContextRegisterToolOptions options = {});
Promise<sequence<RegisteredTool>> getTools(optional ModelContextGetToolOptions options = {});
Promise<DOMString> executeTool(RegisteredTool tool, optional object inputObject = {}, optional ModelContextExecuteToolOptions options = {});
attribute EventHandler ontoolchange;
};
</xmp>
Each {{ModelContext}} object has an associated <dfn for=ModelContext>internal context</dfn>, which
is a [=model context=] [=struct=] created alongside the {{ModelContext}}.
<dl class="domintro">
<dt><code><var ignore>document</var>.{{Document/modelContext}}.{{ModelContext/registerTool(tool, options)}}</code></dt>
<dd>
<p>Registers a tool that [=agents=] can invoke. Returns a rejected promise if a tool with the
same name is already registered, if the given {{ModelContextTool/name}} or
{{ModelContextTool/description}} are empty strings, or if the {{ModelContextTool/inputSchema}}
is invalid.</p>
</dd>
<dt><code><var ignore>document</var>.{{Document/modelContext}}.{{ModelContext/getTools(options)}}</code></dt>
<dd>
<p>Returns a promise that resolves to a list of registered tools from this document and its
descendants that are exposed to this document. This API is designed for so-called "in-page"
agents written in JavaScript, and possibly living in <{iframe}>s. The [=user agent=]'s [=browser
agent=] uses a different internal mechanism to retrieve the tools exposed to it.</p>
</dd>
<dt><code><var ignore>document</var>.{{Document/modelContext}}.{{ModelContext/executeTool(tool, inputObject, options)}}</code></dt>
<dd>
<p>Executes a tool on the document it was registered on. Returns a promise that resolves to the
stringified result of the tool's execution.</p>
</dd>
</dl>
<div algorithm>
The <dfn method for=ModelContext>registerTool(<var>tool</var>, <var>options</var>)</dfn> method steps are:
1. Let |global| be [=this=]'s [=relevant global object=].
1. Let |tool owner| be |global|'s [=associated Document|associated <code>Document</code>=].
1. If |tool owner| is not [=Document/fully active=], then return [=a promise rejected with=] an
"{{InvalidStateError}}" {{DOMException}}.
1. If [=this=]'s [=surrounding agent=]'s [=agent cluster=]'s [=is origin-keyed=] is false
and [=this=]'s [=relevant settings object=]'s [=environment settings object/origin=]'s
[=origin/scheme=] is not <code>"file"</code>, then return [=a promise rejected with=] a
"{{SecurityError}}" {{DOMException}}.
1. If |tool owner| is not [=allowed to use=] the "{{tools}}" feature, then return [=a promise
rejected with=] a "{{NotAllowedError}}" {{DOMException}}.
1. Let |tool map| be [=this=]'s [=ModelContext/internal context=]'s [=model context/tool map=].
1. Let |tool name| be |tool|'s {{ModelContextTool/name}}.
1. Let |tool title| be |tool|'s {{ModelContextTool/title}}.
1. If |tool map|[|tool name|] [=map/exists=], then return [=a promise rejected with=] an
{{InvalidStateError}} {{DOMException}}.
1. If |tool name| or {{ModelContextTool/description}} is an empty string, then return [=a promise
rejected with=] an {{InvalidStateError}} {{DOMException}}.
1. If either |tool name| is the empty string, or its [=string/length=] is greater than 128, or if
|tool name| contains a [=code point=] that is not an [=ASCII alphanumeric=], U+005F (_),
U+002D (-), or U+002E (.), then return [=a promise rejected with=] an {{InvalidStateError}}
{{DOMException}}.
1. Let |stringified input schema| be the empty string.
1. If |tool|'s {{ModelContextTool/inputSchema}} [=map/exists=], then set |stringified input schema|
to the result of [=serializing a JavaScript value to a JSON string=], given |tool|'s
{{ModelContextTool/inputSchema}}. If this threw an exception, then return [=a promise rejected
with=] that exception.
<div class="note">
<p>The serialization algorithm above throws exceptions in the following cases:</p>
<ol>
<li><p><i>Throws a new {{TypeError}}</i> when the backing "<code>JSON.stringify()</code>"
yields undefined, e.g.,
"<code>inputSchema: { toJSON() {return HTMLDivElement;}}</code>", or
"<code>inputSchema: { toJSON() {return undefined;}}</code>".</p></li>
<li><p><i>Re-throws exceptions</i> thrown by "<code>JSON.stringify()</code>", e.g., when
"<code>inputSchema</code>" is an object with a circular reference, etc.</p></li>
</ol>
</div>
1. If |options|'s {{ModelContextRegisterToolOptions/signal}} [=map/exists=] and is
[=AbortSignal/aborted=], then return [=a promise rejected with=] |options|'s
{{ModelContextRegisterToolOptions/signal}}'s [=AbortSignal/abort reason=].
1. Let |exposed origins| be an empty [=list=] of [=origins=].
1. If |options|'s {{ModelContextRegisterToolOptions/exposedTo}} [=map/exists=], then:
1. [=list/For each=] |origin| of |options|'s {{ModelContextRegisterToolOptions/exposedTo}}:
1. Let |parsedURL| be the result of running the [=URL parser=] on |origin|.
1. If |parsedURL| is failure or its [=url/origin=] is not [$is origin potentially
trustworthy?|potentially trustworthy$], then return [=a promise rejected with=] a
"{{SecurityError}}" {{DOMException}}.
1. [=list/Append=] |parsedURL|'s [=url/origin=] to |exposed origins|.
1. Let |promise| be [=a new promise=] created in [=this=]'s [=relevant realm=].
1. If |options|'s {{ModelContextRegisterToolOptions/signal}} [=map/exists=], then:
1. Let |signal| be |options|'s {{ModelContextRegisterToolOptions/signal}}.
1. If |signal| is [=AbortSignal/aborted=], then return [=a promise rejected with=]
|signal|'s [=AbortSignal/abort reason=].
1. [=AbortSignal/add|Add the following abort steps=] to |signal|:
1. [=model context/Unregister a tool=] given [=this=] and |tool name|.
1. [=Reject=] |promise| with |signal|'s [=AbortSignal/abort reason=].
1. Let |tool definition| be a new [=tool definition=], with the following [=struct/items=]:
: [=tool definition/name=]
:: |tool name|
: [=tool definition/title=]
:: |tool title|
: [=tool definition/description=]
:: |tool|'s {{ModelContextTool/description}}
: [=tool definition/input schema=]
:: |stringified input schema|
: [=tool definition/execute steps=]
:: An algorithm that takes a {{Document}} |targetDocument|, a [=string=] |inputArguments|, an
algorithm |completionSteps|, and a [=unique internal value=] |uuid|, and runs the [=imperative
execute steps=] given |tool|, |targetDocument|, |inputArguments|, |completionSteps|, and
|uuid|.
: [=tool definition/annotations=]
:: null if |tool|'s {{ModelContextTool/annotations}} does not [=map/exist=]. Otherwise, an
[=annotations=] with the following [=struct/items=]:
: [=annotations/read-only hint=]
:: |tool|'s {{ModelContextTool/annotations}}'s {{ToolAnnotations/readOnlyHint}}
: [=annotations/untrusted content hint=]
:: |tool|'s {{ModelContextTool/annotations}}'s {{ToolAnnotations/untrustedContentHint}}
: [=tool definition/exposed origins=]
:: |exposed origins|
1. Set [=this=]'s [=ModelContext/internal context=]'s [=model context/tool map=][|tool name|] to
|tool definition|.
1. Run the following steps [=in parallel=]:
1. [=Notify documents of a tool change=] given |tool owner| and |exposed origins|.
1. [=Queue a global task=] on the [=webmcp task source=] given |global| to [=resolve=] |promise|
with undefined.
1. Return |promise|
</div>
<div algorithm>
The <dfn method for=ModelContext>getTools(<var>options</var>)</dfn> method steps are:
1. Let |global| be [=this=]'s [=relevant global object=].
1. Let |toolRequestor| be |global|'s [=associated Document|associated <code>Document</code>=].
1. If |toolRequestor| is not [=Document/fully active=], then return [=a promise rejected with=] an
"{{InvalidStateError}}" {{DOMException}}.
1. If [=this=]'s [=surrounding agent=]'s [=agent cluster=]'s [=is origin-keyed=] is false and [=this=]'s
[=relevant settings object=]'s [=environment settings object/origin=]'s [=origin/scheme=] is not
<code>"file"</code>, then return [=a promise rejected with=] a "{{SecurityError}}"
{{DOMException}}.
1. If |toolRequestor| is not [=allowed to use=] the "{{tools}}" feature, then return [=a promise
rejected with=] a "{{NotAllowedError}}" {{DOMException}}.
1. Let |from origins| be an empty [=list=] of [=origins=].
1. If |options|'s {{ModelContextGetToolOptions/fromOrigins}} [=map/exists=], then:
1. [=list/For each=] |origin| of |options|'s {{ModelContextGetToolOptions/fromOrigins}}:
1. Let |parsedURL| be the result of running the [=URL parser=] on |origin|.
1. If |parsedURL| is failure or its [=url/origin=] is not [$is origin potentially
trustworthy?|potentially trustworthy$], then return [=a promise rejected with=] a
"{{SecurityError}}" {{DOMException}}.
1. [=list/Append=] |parsedURL|'s [=url/origin=] to |from origins|.
1. Let |promise| be [=a new promise=] created in [=this=]'s [=relevant realm=].
1. Run the following steps [=in parallel=]:
1. Let |tools| be an empty [=list=] of {{RegisteredTool}} dictionaries.
1. Let |navigables| be |toolRequestor|'s [=node navigable=]'s [=navigable/traversable
navigable=]'s [=Document/inclusive descendant navigables=].
1. [=list/For each=] |navigable| of |navigables|:
1. Let |targetDocument| be |navigable|'s [=navigable/active document=].
1. If |targetDocument| is not [=allowed to use=] the "{{tools}}" feature, then
[=iteration/continue=].
1. Let |targetOrigin| be |targetDocument|'s [=Document/origin=].
1. Let |callerOrigin| be |toolRequestor|'s [=Document/origin=].
1. If |toolOwnerIsRequested| be true if |targetOrigin| is [=same origin=] with |callerOrigin|,
or if |from origins| [=list/contains=] |targetOrigin|; otherwise, false.
1. If |toolOwnerIsRequested| is false, then [=iteration/continue=].
1. Let |targetToolMap| be |targetDocument|'s [=Document/associated ModelContext|associated
<code>ModelContext</code>=]'s [=ModelContext/internal context=]'s [=model context/tool
map=].
1. [=map/For each=] <var ignore>tool name</var> → |tool definition| of |targetToolMap|:
1. If [=tool is exposed to an origin=] given |targetOrigin|, |tool definition|'s [=tool
definition/exposed origins=], and |callerOrigin| returns false, then
[=iteration/continue=].
1. Let |registeredTool| be a new {{RegisteredTool}} dictionary, with the following fields:
: {{RegisteredTool/name}}
:: |tool definition|'s [=tool definition/name=]
: {{RegisteredTool/title}}
:: |tool definition|'s [=tool definition/title=] if it is non-null; otherwise the empty
string.
Issue(#224): Consider not defaulting to the empty string, and just excluding this
member, which will result in {{undefined}}.
: {{RegisteredTool/description}}
:: |tool definition|'s [=tool definition/description=]
: {{RegisteredTool/inputSchema}}
:: the result of [=parse a JSON string to a JavaScript value=] given |tool
definition|'s [=tool definition/input schema=], if |tool definition|'s [=tool
definition/input schema=] is not the empty string; otherwise undefined.
Note: This will never throw an exception, because the string stored in the tool
definition is always a valid JSON string.
: {{RegisteredTool/window}}
:: |targetDocument|'s [=relevant global object=]
: {{RegisteredTool/origin}}
:: |targetOrigin|, [=serialization of an origin|serialized=].
: {{RegisteredTool/annotations}}
:: if |tool definition|'s [=tool definition/annotations=] is not null, a
{{ToolAnnotations}} dictionary whose {{ToolAnnotations/readOnlyHint}} is |tool
definition|'s [=tool definition/annotations=]'s [=annotations/read-only hint=] and
{{ToolAnnotations/untrustedContentHint}} is |tool definition|'s [=tool
definition/annotations=]'s [=annotations/untrusted content hint=].
1. [=list/Append=] |registeredTool| to |tools|.
1. [=list/Sort in ascending order=] |tools|, with |a| being less than |b| if
|a|["{{RegisteredTool/name}}"] is [=code unit less than=] |b|["{{RegisteredTool/name}}"].
1. [=Queue a global task=] on the [=webmcp task source=] given |global| to [=resolve=] |promise|
with |tools|.
1. Return |promise|.
</div>
<div algorithm>
The <dfn method for=ModelContext>executeTool(<var>tool</var>, <var>inputObject</var>,
<var>options</var>)</dfn> method steps are:
1. Let |callerDocument| be [=this=]'s [=relevant global object=]'s [=associated
Document|associated <code>Document</code>=].
1. If |callerDocument| is not [=Document/fully active=], then return [=a promise rejected with=]
an "{{InvalidStateError}}" {{DOMException}}.
1. If [=this=]'s [=surrounding agent=]'s [=agent cluster=]'s [=is origin-keyed=] is false and
[=this=]'s [=relevant settings object=]'s [=environment settings object/origin=]'s
[=origin/scheme=] is not "<code>file</code>", then return [=a promise rejected with=] a
"{{SecurityError}}" {{DOMException}}.
1. If |callerDocument| is not [=allowed to use=] the "{{tools}}" feature, then return [=a promise
rejected with=] a "{{NotAllowedError}}" {{DOMException}}.
1. Let |expectedTargetOriginURL| be the result of [=URL parser|parsing=] |tool|'s
{{RegisteredTool/origin}}.
1. If |expectedTargetOriginURL| is failure, or |expectedTargetOriginURL|'s [=url/origin=] is an
[=opaque origin=], then return [=a promise rejected with=] a "{{NotSupportedError}}"
{{DOMException}}.
1. Let |expectedTargetOrigin| be |expectedTargetOriginURL|'s [=url/origin=].
1. [=Assert=]: |expectedTargetOrigin| is not an [=opaque origin=].
1. Let |inputArguments| be the result of [=serializing a JavaScript value to a JSON string=] given
|inputObject|. If this threw an exception, then return [=a promise rejected with=] that exception.
1. Let |promise| be [=a new promise=] created in [=this=]'s [=relevant realm=].
1. Let |targetWindow| be |tool|'s {{RegisteredTool/window}}.
1. Let |targetDocument| be |targetWindow|'s [=associated Document|associated
<code>Document</code>=].
1. Let |uuid| be a new [=unique internal value=].
1. If |options|'s {{ModelContextExecuteToolOptions/signal}} [=map/exists=], then:
1. Let |signal| be |options|'s {{ModelContextExecuteToolOptions/signal}}.
1. If |signal| is [=AbortSignal/aborted=], then return [=a promise rejected with=] |signal|'s
[=AbortSignal/abort reason=].
1. Let |traversable| be |targetDocument|'s [=node navigable=]'s [=navigable/traversable
navigable=].
1. [=AbortSignal/add|Add the following abort steps=] to |signal|:
1. [=Reject=] |promise| with |signal|'s [=AbortSignal/abort reason=].
1. [=In parallel=], [=cancel a pending tool execution=] given |traversable| and |uuid|.
1. Run the following steps [=in parallel=]:
1. If |targetDocument|'s [=node navigable=]'s [=navigable/traversable navigable=] is not
|callerDocument|'s [=node navigable=]'s [=navigable/traversable navigable=], then [=queue a
global task=] on the [=webmcp task source=] given |callerDocument|'s [=relevant global
object=] to [=reject=] |promise| with an "{{UnknownError}}" {{DOMException}}, and abort these
steps.
Issue(#227): Consider supporting tool execution across top-level documents in the same
[=browsing context group=].
Issue: Support more granular errors than "{{UnknownError}}", based on each failure case.
1. Let |targetOrigin| be |targetDocument|'s [=Document/origin=].
1. Let |callerOrigin| be |callerDocument|'s [=Document/origin=].
1. If |targetOrigin| is not [=same origin=] with |expectedTargetOrigin|, then [=queue a global
task=] on the [=webmcp task source=] given |callerDocument|'s [=relevant global object=] to
[=reject=] |promise| with an "{{UnknownError}}" {{DOMException}}, and abort these steps.
Issue: Support more granular errors than "{{UnknownError}}", based on each failure case.
1. Let |targetToolMap| be |targetDocument|'s [=Document/associated ModelContext|associated
<code>ModelContext</code>=]'s [=ModelContext/internal context=]'s [=model context/tool map=].
1. Let |toolName| be |tool|'s {{RegisteredTool/name}}.
1. If |targetToolMap|[|toolName|] does not [=map/exist=], then [=queue a global task=] on the
[=webmcp task source=] given |callerDocument|'s [=relevant global object=] to [=reject=]
|promise| with an "{{UnknownError}}" {{DOMException}}, and abort these steps.
Issue: Support more granular errors than "{{UnknownError}}", based on each failure case.
1. Let |tool definition| be |targetToolMap|[|toolName|].
1. If [=tool is exposed to an origin=] given |targetOrigin|, |tool definition|'s [=tool
definition/exposed origins=], and |callerOrigin| returns false, then [=queue a global task=]
on the [=webmcp task source=] given |callerDocument|'s [=relevant global object=] to
[=reject=] |promise| with an "{{UnknownError}}" {{DOMException}}, and abort these steps.
Issue: Support more granular errors than "{{UnknownError}}", based on each failure case.
1. Let |completionSteps| be an algorithm that takes a [=string=]-or-null |result| and a
[=boolean=] |success|, and runs the following steps:
1. [=Assert=]: these steps are running [=in parallel=].
1. If |targetDocument|'s [=node navigable=]'s [=navigable/traversable navigable=]'s
[=traversable navigable/pending tool executions map=][|uuid|] does not [=map/exist=], then
return.