( tool: ToolDescriptor<InputSchema>, injector?: Injector, )
| 34 | * @experimental |
| 35 | */ |
| 36 | export async function declareExperimentalWebMcpTool<const InputSchema extends object>( |
| 37 | tool: ToolDescriptor<InputSchema>, |
| 38 | injector?: Injector, |
| 39 | ): Promise<void> { |
| 40 | // SSR may not have a document yet, so we abort before checking it. |
| 41 | if (typeof ngServerMode !== 'undefined' && ngServerMode) return; |
| 42 | |
| 43 | // modelContext was moved from `navigator` to `document` in the spec, but we check both for compatibility with different environments. |
| 44 | const modelContext = |
| 45 | (globalThis.document as {modelContext?: ModelContext}).modelContext ?? |
| 46 | (globalThis.navigator as unknown as {modelContext?: ModelContext}).modelContext; |
| 47 | |
| 48 | // Verify WebMCP is supported in this client. The typeof check guards against |
| 49 | // DOM clobbering (e.g. <form id="modelContext">), which would produce a truthy |
| 50 | // Element instead of a ModelContext object. |
| 51 | if (!modelContext || typeof modelContext.registerTool !== 'function') return; |
| 52 | |
| 53 | if (typeof ngDevMode !== 'undefined' && ngDevMode) { |
| 54 | if (!injector) assertInInjectionContext(declareExperimentalWebMcpTool); |
| 55 | } |
| 56 | |
| 57 | // Inject the `DestroyRef` and `Injector` immediately, so if it fails we abort |
| 58 | // before causing any side effects. |
| 59 | const currentInjector = injector ?? inject(Injector); |
| 60 | const destroyRef = currentInjector.get(DestroyRef); |
| 61 | |
| 62 | // Wrap the input tool with an `AbortSignal` which aborts when the |
| 63 | // injection context is destroyed. |
| 64 | const abortCtrl = new AbortController(); |
| 65 | const wrappedTool: ModelContextTool = { |
| 66 | ...tool, |
| 67 | execute: (args, client) => { |
| 68 | // Remove the optional chaining when it is updated to match Chrome 153 spec. |
| 69 | const signal = client?.signal |
| 70 | ? AbortSignal.any([abortCtrl.signal, client.signal]) |
| 71 | : abortCtrl.signal; |
| 72 | |
| 73 | return runInInjectionContext(currentInjector, () => |
| 74 | tool.execute(args as Parameters<typeof tool.execute>[0], { |
| 75 | ...client, |
| 76 | signal, |
| 77 | }), |
| 78 | ); |
| 79 | }, |
| 80 | }; |
| 81 | |
| 82 | // Unregister when the associated `Injector` is destroyed. |
| 83 | destroyRef.onDestroy(() => void abortCtrl.abort()); |
| 84 | |
| 85 | try { |
| 86 | await modelContext.registerTool(wrappedTool, {signal: abortCtrl.signal}); |
| 87 | } catch (error: unknown) { |
| 88 | if (error instanceof DOMException && error.name === 'AbortError') { |
| 89 | // This happens when an Injector is created and then immediately destroyed |
| 90 | // such that the onDestroy above gets called before registerTool resolves |
| 91 | // We don't mind swallowing the error in this case. |
| 92 | return; |
| 93 | } |
no test coverage detected