-
Notifications
You must be signed in to change notification settings - Fork 85
Surface tools registered through a navigator.modelContext polyfill #416
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rgarcia
wants to merge
4
commits into
main
Choose a base branch
from
hypeship/webmcp-polyfill-tools
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
cf0efd7
Surface tools registered through a navigator.modelContext polyfill
rgarcia eccd1f6
Harden polyfill discovery and invocation
rgarcia 33b8e10
Bridge polyfill tools into the native registry
rgarcia a416c47
Rebridge a replaced document within the same listing
rgarcia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| package e2e | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "net/http" | ||
| "os" | ||
| "testing" | ||
| "time" | ||
|
|
||
| instanceoapi "github.com/kernel/kernel-images/server/lib/oapi" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| // testWebMCPPolyfill covers tools that a page registers through its own | ||
| // navigator.modelContext polyfill instead of the native document.modelContext | ||
| // registry: late installation, same-origin embedded frames, native precedence | ||
| // for a shared name, invocation results, unregistration, and navigation. | ||
| func testWebMCPPolyfill(t *testing.T, ctx context.Context, client *instanceoapi.ClientWithResponses) { | ||
| t.Helper() | ||
|
|
||
| fixture, err := os.ReadFile("testdata/webmcp/polyfill.html") | ||
| require.NoError(t, err) | ||
| written, err := client.WriteFileWithBodyWithResponse(ctx, | ||
| &instanceoapi.WriteFileParams{Path: "/tmp/polyfill.html"}, "text/html", bytes.NewReader(fixture)) | ||
| require.NoError(t, err) | ||
| require.Equal(t, http.StatusCreated, written.StatusCode(), "%s", written.Body) | ||
|
|
||
| const pageURL = "file:///tmp/polyfill.html" | ||
| var readyState string | ||
| executeWebMCPPlaywright(t, ctx, client, ` | ||
| await page.goto('file:///tmp/polyfill.html', { waitUntil: 'load' }); | ||
| return page.evaluate(() => document.readyState); | ||
| `, &readyState) | ||
| require.Equal(t, "complete", readyState) | ||
|
|
||
| toolsByName := func(collect *assert.CollectT) map[string]instanceoapi.WebMCPTool { | ||
| rsp, err := client.GetWebMCPToolsWithResponse(ctx, &instanceoapi.GetWebMCPToolsParams{}) | ||
| if !assert.NoError(collect, err) || !assert.Equal(collect, http.StatusOK, rsp.StatusCode(), "%s", rsp.Body) || rsp.JSON200 == nil { | ||
| return nil | ||
| } | ||
| tools := make(map[string]instanceoapi.WebMCPTool) | ||
| for _, tool := range rsp.JSON200.Tools { | ||
| if tool.Source.PageUrl == pageURL { | ||
| tools[tool.Tool.Name] = tool | ||
| } | ||
| } | ||
| return tools | ||
| } | ||
|
|
||
| // The polyfill installs 1.5s after load; discovery picks it up on a later listing. | ||
| var tools map[string]instanceoapi.WebMCPTool | ||
| require.EventuallyWithT(t, func(collect *assert.CollectT) { | ||
| tools = toolsByName(collect) | ||
| for _, name := range []string{"search_items", "shared_name", "failing_tool", "navigate_away", "frame_tool"} { | ||
| assert.Contains(collect, tools, name) | ||
| } | ||
| }, 15*time.Second, 250*time.Millisecond) | ||
| t.Logf("GET /webmcp/tools: %d tools on %s", len(tools), pageURL) | ||
|
|
||
| search := tools["search_items"] | ||
| require.Nil(t, search.Source.Frame) | ||
| require.Nil(t, search.Source.Custom) | ||
| require.Equal(t, "Search the catalog.", search.Tool.Description) | ||
| require.Equal(t, []any{"query"}, search.Tool.InputSchema["required"]) | ||
|
|
||
| // The same name registered natively lists once, as the native tool. | ||
| shared := tools["shared_name"] | ||
| require.Equal(t, "Native copy.", shared.Tool.Description) | ||
|
|
||
| frameTool := tools["frame_tool"] | ||
| require.NotNil(t, frameTool.Source.Frame) | ||
| require.Equal(t, "about:srcdoc", frameTool.Source.Frame.Url) | ||
|
|
||
| timeout := 10 | ||
| invoke := func(ref string, input map[string]any) *instanceoapi.InvokeWebMCPToolResponse { | ||
| rsp, err := client.InvokeWebMCPToolWithResponse(ctx, instanceoapi.WebMCPInvokeRequest{ | ||
| ToolRef: ref, Input: input, TimeoutSec: &timeout, | ||
| }) | ||
| require.NoError(t, err) | ||
| t.Logf("POST /webmcp/invoke %s: %s", ref, rsp.Body) | ||
| return rsp | ||
| } | ||
|
|
||
| searched := invoke(search.ToolRef, map[string]any{"query": "lamp"}) | ||
| require.Equal(t, http.StatusOK, searched.StatusCode(), "%s", searched.Body) | ||
| require.NotNil(t, searched.JSON200) | ||
| require.Equal(t, instanceoapi.WebMCPInvocationResultStatusCompleted, searched.JSON200.Status) | ||
| require.NotEmpty(t, searched.JSON200.InvocationId) | ||
| require.Equal(t, map[string]any{"results": []any{"match for lamp"}, "page": "/tmp/polyfill.html"}, searched.JSON200.Output) | ||
|
|
||
| var logText string | ||
| executeWebMCPPlaywright(t, ctx, client, `return page.evaluate(() => document.querySelector('#log').textContent);`, &logText) | ||
| require.Equal(t, "searched lamp", logText) | ||
|
|
||
| framed := invoke(frameTool.ToolRef, map[string]any{"item": 1}) | ||
| require.Equal(t, http.StatusOK, framed.StatusCode(), "%s", framed.Body) | ||
| require.Equal(t, map[string]any{"frame": "Embedded polyfill catalog", "input": map[string]any{"item": float64(1)}}, framed.JSON200.Output) | ||
|
|
||
| native := invoke(shared.ToolRef, map[string]any{}) | ||
| require.Equal(t, http.StatusOK, native.StatusCode(), "%s", native.Body) | ||
| require.Equal(t, map[string]any{"source": "native"}, native.JSON200.Output) | ||
|
|
||
| failed := invoke(tools["failing_tool"].ToolRef, map[string]any{}) | ||
| require.Equal(t, http.StatusOK, failed.StatusCode(), "%s", failed.Body) | ||
| require.Equal(t, instanceoapi.WebMCPInvocationResultStatusError, failed.JSON200.Status) | ||
|
|
||
| // Unregistration through the polyfill drops the tool on the next listing, | ||
| // and the surviving tool keeps its reference. | ||
| var clicked bool | ||
| executeWebMCPPlaywright(t, ctx, client, `await page.click('#unregister'); return true;`, &clicked) | ||
| require.True(t, clicked) | ||
| require.EventuallyWithT(t, func(collect *assert.CollectT) { | ||
| tools = toolsByName(collect) | ||
| assert.NotContains(collect, tools, "failing_tool") | ||
| assert.Equal(collect, search.ToolRef, tools["search_items"].ToolRef) | ||
| }, 10*time.Second, 250*time.Millisecond) | ||
|
|
||
| // A tool that navigates its document completes like a native one and the | ||
| // old registrations disappear with the document. | ||
| tabID := search.Source.TabId | ||
| navigated := invoke(tools["navigate_away"].ToolRef, map[string]any{}) | ||
| require.Equal(t, http.StatusOK, navigated.StatusCode(), "%s", navigated.Body) | ||
| require.Equal(t, instanceoapi.WebMCPInvocationResultStatusCompleted, navigated.JSON200.Status) | ||
| require.Equal(t, []any{}, navigated.JSON200.Output) | ||
| require.EventuallyWithT(t, func(collect *assert.CollectT) { | ||
| rsp, err := client.GetWebMCPToolsWithResponse(ctx, &instanceoapi.GetWebMCPToolsParams{}) | ||
| if !assert.NoError(collect, err) || !assert.Equal(collect, http.StatusOK, rsp.StatusCode(), "%s", rsp.Body) || rsp.JSON200 == nil { | ||
| return | ||
| } | ||
| for _, tool := range rsp.JSON200.Tools { | ||
| assert.NotEqual(collect, tabID, tool.Source.TabId, "%s survived navigation", tool.Tool.Name) | ||
| } | ||
| }, 10*time.Second, 250*time.Millisecond) | ||
| stale := invoke(search.ToolRef, map[string]any{"query": "x"}) | ||
| require.Equal(t, http.StatusNotFound, stale.StatusCode(), "%s", stale.Body) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| <!doctype html> | ||
| <html lang="en"> | ||
| <head> | ||
| <meta charset="utf-8"> | ||
| <title>Polyfill catalog</title> | ||
| </head> | ||
| <body> | ||
| <h1>Catalog</h1> | ||
| <p id="log" role="status"></p> | ||
| <button id="unregister" type="button">Remove failing tool</button> | ||
| <!-- A same-origin child document with its own registry-style polyfill. --> | ||
| <iframe title="Embedded catalog" width="600" height="300" srcdoc=" | ||
| <title>Embedded polyfill catalog</title> | ||
| <script> | ||
| const registry = new Map(); | ||
| navigator.modelContext = { | ||
| _registeredTools: registry, | ||
| registerTool(tool) { registry.set(tool.name, tool); }, | ||
| unregisterTool(name) { registry.delete(name); }, | ||
| listTools: () => [...registry.values()].map(({execute, ...metadata}) => metadata), | ||
| async callTool(name, input) { return registry.get(name).execute(input); }, | ||
| }; | ||
| navigator.modelContext.registerTool({ | ||
| name: 'frame_tool', | ||
| description: 'Registered by the embedded document.', | ||
| inputSchema: {type: 'object'}, | ||
| execute: async (input) => ({frame: document.title, input}), | ||
| }); | ||
| </script> | ||
| "></iframe> | ||
| <!-- Mirrors sites that ship WebMCP tools through their own navigator.modelContext | ||
| polyfill: a registry object plus registerTool/unregisterTool/listTools/callTool. | ||
| The polyfill installs after a delay, like a lazily loaded site bundle. --> | ||
| <script> | ||
| function installPolyfill() { | ||
| if ('modelContext' in navigator) return; | ||
| const registry = {}; | ||
| navigator.modelContext = { | ||
| _registeredTools: registry, | ||
| registerTool(tool, options) { | ||
| registry[tool.name] = { | ||
| name: tool.name, | ||
| title: tool.title, | ||
| description: tool.description, | ||
| inputSchema: tool.inputSchema ?? tool.parameters, | ||
| execute: tool.execute, | ||
| }; | ||
| const signal = options?.signal ?? tool.signal; | ||
| signal?.addEventListener('abort', () => delete registry[tool.name], {once: true}); | ||
| }, | ||
| unregisterTool(name) { | ||
| delete registry[name]; | ||
| }, | ||
| async callTool(name, input) { | ||
| const tool = registry[name]; | ||
| if (!tool) throw new Error(`Tool not found: ${name}`); | ||
| return tool.execute(input, undefined); | ||
| }, | ||
| listTools: () => Object.values(registry).map((tool) => ({ | ||
| name: tool.name, | ||
| description: tool.description, | ||
| inputSchema: tool.inputSchema, | ||
| })), | ||
| }; | ||
| } | ||
|
|
||
| function registerTools() { | ||
| navigator.modelContext.registerTool({ | ||
| name: 'search_items', | ||
| description: 'Search the catalog.', | ||
| inputSchema: {type: 'object', properties: {query: {type: 'string'}}, required: ['query']}, | ||
| execute: async (input) => { | ||
| document.querySelector('#log').textContent = `searched ${input.query}`; | ||
| return {results: [`match for ${input.query}`], page: location.pathname}; | ||
| }, | ||
| }); | ||
| navigator.modelContext.registerTool({ | ||
| name: 'shared_name', | ||
| description: 'Polyfill copy.', | ||
| inputSchema: {type: 'object'}, | ||
| execute: async () => ({source: 'polyfill'}), | ||
| }); | ||
| navigator.modelContext.registerTool({ | ||
| name: 'failing_tool', | ||
| description: 'Always throws.', | ||
| inputSchema: {type: 'object'}, | ||
| execute: async () => { | ||
| throw new Error('nothing to do'); | ||
| }, | ||
| }); | ||
| navigator.modelContext.registerTool({ | ||
| name: 'navigate_away', | ||
| description: 'Navigates the page and never resolves.', | ||
| inputSchema: {type: 'object'}, | ||
| execute: async () => { | ||
| location.href = 'about:blank'; | ||
| return new Promise(() => {}); | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| // The same name registered natively must win over the polyfill copy. | ||
| document.modelContext.registerTool({ | ||
| name: 'shared_name', | ||
| description: 'Native copy.', | ||
| inputSchema: {type: 'object'}, | ||
| execute: async () => ({source: 'native'}), | ||
| }); | ||
|
|
||
| document.querySelector('#unregister').addEventListener('click', () => { | ||
| navigator.modelContext.unregisterTool('failing_tool'); | ||
| }); | ||
|
|
||
| setTimeout(() => { | ||
| installPolyfill(); | ||
| registerTools(); | ||
| }, 1500); | ||
| </script> | ||
| </body> | ||
| </html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the
errorText == "nothing to do"assertion was dropped in the rewrite. does the page's thrown message still reach the caller throughWebMCP.toolResponded, or does the native domain replace it? if callers now get a generic error, a note in the PR body would help, since the previous revision returned the page's message.