Branchwell

OpenTalon / app · opentalon.ai / native / runtime / mcp-bridge.cjs

1#!/usr/bin/env node
2const fs = require('node:fs')
3const path = require('node:path')
4const os = require('node:os')
5const { spawn } = require('node:child_process')
6const readline = require('node:readline')
7const configFile = () =>
8 process.env.OPENTALON_MCP_CONFIG ||
9 path.join(os.homedir(), 'Library', 'Application Support', 'OpenTalon Prototype', 'mcp.json')
10const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
11let launchJob
12function readConfig(file) {
13 const info = fs.statSync(file)
14 if ((info.mode & 0o077) !== 0 || (process.getuid && info.uid !== process.getuid()))
15 throw new Error('OpenTalon connection file must be owned by you and readable only by you.')
16 const config = JSON.parse(fs.readFileSync(file, 'utf8'))
17 if (!config.enabled)
18 throw new Error(
19 'OpenTalon’s MCP connection is disabled. Enable it locally in Settings → Agent connection.'
20 )
21 if (
22 typeof config.token !== 'string' ||
23 config.token.length < 32 ||
24 !path.isAbsolute(config.executable) ||
25 !Array.isArray(config.launchArgs) ||
26 !config.launchArgs.every((arg) => typeof arg === 'string')
27 )
28 throw new Error(
29 'OpenTalon’s connection configuration is invalid. Reopen the app to repair setup.'
30 )
31 return config
32}
33async function request(config, message) {
34 return fetch(`http://127.0.0.1:${config.port}/mcp`, {
35 method: 'POST',
36 headers: {
37 'Content-Type': 'application/json',
38 Accept: 'application/json, text/event-stream',
39 Authorization: `Bearer ${config.token}`,
40 },
41 body: JSON.stringify(message),
42 signal: AbortSignal.timeout(60000),
43 })
44}
45async function ready(file) {
46 const config = readConfig(file)
47 const env = { ...process.env, OPENTALON_PROFILE: config.profile }
48 delete env.ELECTRON_RUN_AS_NODE
49 const child = spawn(config.executable, [...config.launchArgs, '--background'], {
50 detached: true,
51 stdio: 'ignore',
52 env,
53 })
54 let launchError
55 child.on('error', (error) => {
56 launchError = error
57 })
58 child.unref()
59 for (let attempt = 0; attempt < 100; attempt++) {
60 if (launchError) throw new Error('OpenTalon could not start. Check the installed app path.')
61 await pause(150)
62 const latest = readConfig(file)
63 try {
64 const response = await request(latest, { jsonrpc: '2.0', id: 'ready', method: 'ping' })
65 if (response.ok) return latest
66 } catch {}
67 }
68 throw new Error(
69 'OpenTalon did not become ready. Open the app to check its local database or connection error.'
70 )
71}
72async function forward(message, file = configFile()) {
73 const fail = (messageText) =>
74 message?.id !== undefined
75 ? { jsonrpc: '2.0', id: message.id, error: { code: -32000, message: messageText } }
76 : null
77 try {
78 let config = readConfig(file),
79 response
80 try {
81 response = await request(config, message)
82 } catch {
83 if (process.env.OPENTALON_MCP_NO_LAUNCH === '1') return fail('This chat connection is closed.')
84 launchJob ||= ready(file).finally(() => {
85 launchJob = null
86 })
87 config = await launchJob
88 // Every mutation carries a durable requestKey; retrying an uncertain response is safe.
89 response = await request(config, message)
90 }
91 if (response.status === 202 || response.status === 204) return null
92 if (response.status === 401) {
93 config = readConfig(file)
94 response = await request(config, message)
95 }
96 if (!response.ok)
97 return fail(
98 `OpenTalon refused this request (${response.status}). Check the local connection settings.`
99 )
100 return await response.json()
101 } catch (error) {
102 return fail(
103 error.code === 'ENOENT'
104 ? 'OpenTalon is not set up. Open the app and enable Settings → Agent connection.'
105 : error.message
106 )
107 }
108}
109function main() {
110 const lines = readline.createInterface({ input: process.stdin })
111 let queue = Promise.resolve()
112 lines.on('line', (line) => {
113 queue = queue.then(async () => {
114 let response
115 try {
116 if (Buffer.byteLength(line) > 1024 * 1024) throw new Error('Request too large.')
117 response = await forward(JSON.parse(line))
118 } catch {
119 response = {
120 jsonrpc: '2.0',
121 id: null,
122 error: { code: -32700, message: 'Invalid or oversized JSON message.' },
123 }
124 }
125 if (response) process.stdout.write(`${JSON.stringify(response)}\n`)
126 })
127 })
128 lines.on('close', () => {
129 queue.then(() => {
130 process.exitCode = 0
131 })
132 })
133}
134if (require.main === module) main()
135module.exports = { forward, configFile, readConfig, main }