Branchwell

OpenTalon / app · opentalon.ai / native / runtime / mcp.test.cjs

Raw 7.6 KB on d82caf36fa99426fea138f030e7704d2b3cf17b3
1const test = require('node:test')
2const { tools } = require('./contracts.cjs')
3const assert = require('node:assert/strict')
4const fs = require('node:fs')
5const path = require('node:path')
6const http = require('node:http')
7const { spawn } = require('node:child_process')
8const { randomUUID } = require('node:crypto')
9const { Store } = require('./store.cjs')
10const { Connector } = require('./mcp.cjs')
11const { forward } = require('./mcp-bridge.cjs')
12const base = process.env.OPENTALON_TEST_ROOT || '/Volumes/Expand/Projects/OpenTalon/native-app/tests'
13async function fixture(t) {
14 fs.mkdirSync(base, { recursive: true })
15 const folder = fs.mkdtempSync(path.join(base, 'mcp-'))
16 let changes = 0
17 const store = new Store(folder, { changed: () => changes++ })
18 const connector = new Connector({ folder, call: (name, args) => store.dispatch(name, args) })
19 await connector.enable(true)
20 t.after(async () => {
21 await connector.stop()
22 await store.queue
23 store.close()
24 fs.rmSync(folder, { recursive: true, force: true })
25 })
26 const config = JSON.parse(fs.readFileSync(connector.file, 'utf8'))
27 const headers = {
28 'Content-Type': 'application/json',
29 Accept: 'application/json, text/event-stream',
30 Authorization: `Bearer ${config.token}`,
31 }
32 const rpc = async (message, extraHeaders = {}, body) =>
33 fetch(connector.status().endpoint, {
34 method: 'POST',
35 headers: { ...headers, ...extraHeaders },
36 body: body || JSON.stringify(message),
37 })
38 const call = async (name, args = {}) => {
39 const response = await rpc({
40 jsonrpc: '2.0',
41 id: randomUUID(),
42 method: 'tools/call',
43 params: { name, arguments: args },
44 })
45 const result = (await response.json()).result
46 if (result.isError) {
47 const error = new Error(result.structuredContent.message)
48 error.code = result.structuredContent.code
49 throw error
50 }
51 return result.structuredContent
52 }
53 const write = (name, args = {}) => call(name, { requestKey: randomUUID(), ...args })
54 return {
55 folder,
56 store,
57 connector,
58 rpc,
59 call,
60 write,
61 get changes() {
62 return changes
63 },
64 }
65}
66
67test('real HTTP MCP handshake, discovery, shared actions and guarded recovery', async (t) => {
68 const f = await fixture(t),
69 { call, write, rpc, store } = f
70 const initialized = await rpc({
71 jsonrpc: '2.0',
72 id: 1,
73 method: 'initialize',
74 params: {
75 protocolVersion: '2025-11-25',
76 capabilities: {},
77 clientInfo: { name: 'OpenTalon integration test', version: '1' },
78 },
79 })
80 assert.equal((await initialized.json()).result.serverInfo.name, 'OpenTalon')
81 const notification = await rpc({ jsonrpc: '2.0', method: 'notifications/initialized' })
82 assert.equal(notification.status, 202)
83 const discovery = await rpc({ jsonrpc: '2.0', id: 2, method: 'tools/list' })
84 assert.deepEqual((await discovery.json()).result.tools.map((tool) => tool.name).sort(), tools.map((tool) => tool.name).sort())
85 let board = (await write('create_board', { name: 'From agent' })).board
86 board = (
87 await write('rename_board', { id: board.id, name: 'Renamed', expectedRevision: board.revision })
88 ).board
89 let a = (
90 await write('create_task', {
91 boardId: board.id,
92 title: 'Agent task',
93 notes: 'Searchable context',
94 })
95 ).task
96 const b = (await write('create_task', { boardId: board.id, title: 'Other task' })).task
97 a = (await write('move_task', { id: a.id, afterId: b.id, expectedRevision: a.revision })).task
98 assert.equal((await call('list_tasks', { query: 'Searchable' })).tasks[0].id, a.id)
99 assert.equal(store.task(a.id).notes, 'Searchable context')
100 a = (
101 await store.dispatch('update_task', {
102 id: a.id,
103 title: 'UI path',
104 expectedRevision: a.revision,
105 requestKey: randomUUID(),
106 })
107 ).task
108 assert.equal((await call('get_task', { id: a.id })).task.title, 'UI path')
109 a = (await write('update_task', { id: a.id, status: 'Done', expectedRevision: a.revision })).task
110 a = (
111 await write('move_task', {
112 id: a.id,
113 boardId: store.boards()[0].id,
114 status: 'In progress',
115 expectedRevision: a.revision,
116 })
117 ).task
118 a = (await write('trash_task', { id: a.id, expectedRevision: a.revision })).task
119 a = (await write('restore_task', { id: a.id, expectedRevision: a.revision })).task
120 const backup = await write('create_backup')
121 const inspected = await call('inspect_backup', { path: backup.path })
122 assert.equal(inspected.tasks, 2)
123 const preview = await call('preview_destructive_action', {
124 action: 'restore_backup',
125 path: backup.path,
126 })
127 await write('confirm_destructive_action', { token: preview.token })
128 assert.ok(f.changes >= 10)
129 assert.ok(!JSON.stringify(await call('get_app_status')).includes('token'))
130 const bridged = await forward(
131 {
132 jsonrpc: '2.0',
133 id: 3,
134 method: 'tools/call',
135 params: { name: 'get_task', arguments: { id: a.id } },
136 },
137 f.connector.file
138 )
139 assert.equal(bridged.result.structuredContent.task.title, 'UI path')
140})
141
142test('connection protection, bounded requests, disabled listener, independent ports', async (t) => {
143 const f = await fixture(t),
144 { rpc, connector } = f
145 const ping = { jsonrpc: '2.0', id: 1, method: 'ping' }
146 assert.equal((await rpc(ping, { Authorization: 'Bearer wrong' })).status, 401)
147 assert.equal((await rpc(ping, { Origin: 'https://example.com' })).status, 403)
148 const foreignHost = await new Promise((resolve, reject) => {
149 const request = http.request(
150 connector.status().endpoint,
151 { method: 'POST', headers: { Host: 'evil.example' } },
152 (response) => {
153 response.resume()
154 resolve(response.statusCode)
155 }
156 )
157 request.on('error', reject)
158 request.end(JSON.stringify(ping))
159 })
160 assert.equal(foreignHost, 403)
161 assert.equal((await rpc(ping, {}, 'x'.repeat(15 * 1024 * 1024 + 1))).status, 413)
162 assert.equal((await rpc(ping, {}, '[{}]')).status, 400)
163 assert.equal(fs.statSync(connector.file).mode & 0o777, 0o600)
164 const oldConfig = JSON.parse(fs.readFileSync(connector.file, 'utf8'))
165 connector.reset()
166 assert.notEqual(JSON.parse(fs.readFileSync(connector.file, 'utf8')).token, oldConfig.token)
167 assert.equal((await rpc(ping)).status, 401)
168 const other = await fixture(t)
169 assert.notEqual(connector.config.port, other.connector.config.port)
170 await connector.enable(false)
171 const disabled = await forward(ping, connector.file)
172 assert.match(disabled.error.message, /disabled/)
173 assert.equal(connector.status().running, false)
174})
175
176test('stdio bridge sends only valid JSON-RPC and uses no standalone server', async (t) => {
177 const f = await fixture(t)
178 const input = [
179 { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18' } },
180 { jsonrpc: '2.0', method: 'notifications/initialized' },
181 { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'list_boards' } },
182 ]
183 const child = spawn(process.execPath, [path.join(__dirname, 'mcp-bridge.cjs')], {
184 env: { ...process.env, ELECTRON_RUN_AS_NODE: '1', OPENTALON_MCP_CONFIG: f.connector.file },
185 stdio: ['pipe', 'pipe', 'pipe'],
186 })
187 let stdout = '',
188 stderr = ''
189 child.stdout.on('data', (data) => (stdout += data))
190 child.stderr.on('data', (data) => (stderr += data))
191 child.stdin.end(input.map((message) => JSON.stringify(message)).join('\n') + '\n')
192 await new Promise((resolve, reject) => {
193 child.on('error', reject)
194 child.on('close', (code) => (code ? reject(new Error(stderr)) : resolve()))
195 })
196 const responses = stdout
197 .trim()
198 .split('\n')
199 .map((line) => JSON.parse(line))
200 assert.equal(responses.length, 2)
201 assert.equal(responses[1].result.structuredContent.boards[0].name, 'Tasks')
202})