|
| 1 | +import type { StandardSchemaV1 } from '@standard-schema/spec' |
| 2 | +import { describe, expect, it } from 'vitest' |
| 3 | +import { listBrowserAgentTools } from '../client/browser-agent' |
| 4 | +import { createPageScriptChannel } from './page-script' |
| 5 | + |
| 6 | +interface TestProtocol { |
| 7 | + pageScript: { |
| 8 | + add: (a: number, b: number) => { sum: number } |
| 9 | + hidden: () => string |
| 10 | + } |
| 11 | +} |
| 12 | + |
| 13 | +function schema<T>(json: Record<string, unknown>): StandardSchemaV1<T> { |
| 14 | + return { |
| 15 | + '~standard': { |
| 16 | + version: 1, |
| 17 | + vendor: 'test', |
| 18 | + validate: (value: unknown) => ({ value: value as T }), |
| 19 | + jsonSchema: { |
| 20 | + input: () => json, |
| 21 | + output: () => json, |
| 22 | + }, |
| 23 | + } as StandardSchemaV1<T>['~standard'], |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +describe('in-page channel agent tools', () => { |
| 28 | + it('registers the original handler for browser-to-node agent transport', async () => { |
| 29 | + const channel = createPageScriptChannel<TestProtocol>({ |
| 30 | + name: 'devframes:test', |
| 31 | + window: false, |
| 32 | + heartbeat: false, |
| 33 | + functions: { |
| 34 | + add: { |
| 35 | + jsonSerializable: true, |
| 36 | + agent: { description: 'Add two numbers.' }, |
| 37 | + args: [schema<number>({ type: 'number' }), schema<number>({ type: 'number' })], |
| 38 | + returns: schema<{ sum: number }>({ type: 'object' }), |
| 39 | + handler: (a, b) => ({ sum: a + b }), |
| 40 | + }, |
| 41 | + hidden: { handler: () => 'internal' }, |
| 42 | + }, |
| 43 | + }) |
| 44 | + |
| 45 | + const tool = listBrowserAgentTools().find(tool => tool.id === 'devframes:test:add')! |
| 46 | + expect(tool).toMatchObject({ |
| 47 | + description: 'Add two numbers.', |
| 48 | + safety: 'read', |
| 49 | + inputSchema: { |
| 50 | + type: 'object', |
| 51 | + properties: { arg0: { type: 'number' }, arg1: { type: 'number' } }, |
| 52 | + required: ['arg0', 'arg1'], |
| 53 | + additionalProperties: false, |
| 54 | + }, |
| 55 | + }) |
| 56 | + await expect(tool.invoke({ arg0: 2, arg1: 3 })).resolves.toEqual({ sum: 5 }) |
| 57 | + |
| 58 | + channel.close() |
| 59 | + expect(listBrowserAgentTools().some(tool => tool.id === 'devframes:test:add')).toBe(false) |
| 60 | + }) |
| 61 | + |
| 62 | + it('rejects agent exposure without strict JSON serialization', () => { |
| 63 | + expect(() => createPageScriptChannel<TestProtocol>({ |
| 64 | + name: 'devframes:invalid', |
| 65 | + window: false, |
| 66 | + functions: { |
| 67 | + add: { |
| 68 | + agent: { description: 'Add two numbers.' }, |
| 69 | + handler: (a, b) => ({ sum: a + b }), |
| 70 | + }, |
| 71 | + hidden: { handler: () => 'internal' }, |
| 72 | + }, |
| 73 | + })).toThrowError(/MCP requires JSON-serializable/) |
| 74 | + }) |
| 75 | +}) |
0 commit comments