OpenTalon / app · opentalon.ai / native / runtime / mcp.cjs
| 1 | const http = require('node:http') |
| 2 | const fs = require('node:fs') |
| 3 | const path = require('node:path') |
| 4 | const { randomBytes, timingSafeEqual } = require('node:crypto') |
| 5 | const { tools, validateAction, AppError } = require('./contracts.cjs') |
| 6 | const MAX_BODY = 15 * 1024 * 1024 |
| 7 | const PROTOCOLS = ['2025-11-25', '2025-06-18', '2025-03-26'] |
| 8 | const sqliteErrors = { |
| 9 | 1: ['SQLITE_ERROR', 'SQLite could not execute the operation. Check for an OpenTalon update.'], |
| 10 | 5: ['SQLITE_BUSY', 'Another connection is using the workspace database. Wait briefly, then retry.'], |
| 11 | 6: ['SQLITE_LOCKED', 'A database operation is holding a lock. Let it finish, then retry.'], |
| 12 | 8: ['SQLITE_READONLY', 'SQLite cannot write to the workspace database. Check the data folder permissions and whether its drive is read-only.'], |
| 13 | 10: ['SQLITE_IOERR', 'SQLite encountered a disk I/O error. Check the workspace drive and available space.'], |
| 14 | 11: ['SQLITE_CORRUPT', 'SQLite detected database corruption. Check the workspace in OpenTalon and review your available backups.'], |
| 15 | 13: ['SQLITE_FULL', 'SQLite ran out of space. Free space on the workspace drive and retry.'], |
| 16 | 14: ['SQLITE_CANTOPEN', 'SQLite could not open a database file. Check that the data folder is accessible.'], |
| 17 | 19: ['SQLITE_CONSTRAINT', 'A database constraint prevented the operation. Refresh the affected records before retrying.'], |
| 18 | 787: ['SQLITE_CONSTRAINT_FOREIGNKEY', 'A referenced database record could not be linked. Refresh the task and any linked records before retrying.'], |
| 19 | } |
| 20 | function errorView(error, operation) { |
| 21 | if (error.code === 'ERR_SQLITE_ERROR' && Number.isInteger(error.errcode)) { |
| 22 | // SQLite stores the primary result code in the low byte of an extended code. |
| 23 | const [sqliteCode, hint] = sqliteErrors[error.errcode] ?? sqliteErrors[error.errcode & 0xff] ?? |
| 24 | ['SQLite result', 'SQLite could not complete the operation. Check the workspace in OpenTalon.'] |
| 25 | // Ordinary mutations save their receipt in the same transaction. Backups |
| 26 | // and restore confirmations can also write files outside that transaction. |
| 27 | const sameRequestKeySafe = tools.some(({ name, mutates }) => name === operation && mutates) && |
| 28 | operation !== 'create_backup' && operation !== 'confirm_destructive_action' |
| 29 | return { |
| 30 | code: error.code, |
| 31 | message: `${sqliteCode} (${error.errcode}). ${hint}` + |
| 32 | (sameRequestKeySafe ? ' An identical retry with the same requestKey is safe.' : ''), |
| 33 | details: { |
| 34 | sqliteCode, sqliteResultCode: error.errcode, |
| 35 | ...(sameRequestKeySafe ? { sameRequestKeySafe } : {}), |
| 36 | }, |
| 37 | } |
| 38 | } |
| 39 | if (operation === 'create_backup' && !(error instanceof AppError)) { |
| 40 | const hint = { |
| 41 | ENOENT: 'The backup destination is unavailable. Reconnect its drive or choose an existing destination folder.', |
| 42 | ENOTDIR: 'Part of the backup destination is not a folder. Choose an existing destination folder.', |
| 43 | EACCES: 'OpenTalon lacks permission to write the backup. Choose a writable destination.', |
| 44 | EPERM: 'OpenTalon lacks permission to write the backup. Choose a writable destination.', |
| 45 | EROFS: 'The backup destination is read-only. Choose a writable destination.', |
| 46 | ENOSPC: 'The backup could not be written because the disk is full. Free space or choose another destination.', |
| 47 | EIO: 'The backup encountered a disk I/O error. Check the destination drive before retrying.', |
| 48 | }[error.code] |
| 49 | if (hint) return { code: error.code, message: hint } |
| 50 | } |
| 51 | return { |
| 52 | code: error.code || 'SAVE_FAILED', |
| 53 | message: |
| 54 | error instanceof AppError |
| 55 | ? error.message |
| 56 | : 'OpenTalon could not complete the local operation. Check the app and verify the result before retrying.', |
| 57 | ...(error.details ? { details: error.details } : {}), |
| 58 | } |
| 59 | } |
| 60 | class Connector { |
| 61 | constructor({ |
| 62 | folder, |
| 63 | call, |
| 64 | executable = process.execPath, |
| 65 | launchArgs = [], |
| 66 | stdioCommand, |
| 67 | version = '0.1.0', |
| 68 | changed = () => {}, |
| 69 | toolCatalog = tools, |
| 70 | }) { |
| 71 | Object.assign(this, { folder, call, executable, launchArgs, stdioCommand, version, changed, toolCatalog }) |
| 72 | this.file = path.join(folder, 'mcp.json') |
| 73 | this.server = null |
| 74 | this.error = '' |
| 75 | let saved = {} |
| 76 | try { |
| 77 | saved = JSON.parse(fs.readFileSync(this.file, 'utf8')) |
| 78 | } catch (error) { |
| 79 | if (error.code !== 'ENOENT') |
| 80 | throw new AppError( |
| 81 | 'CONNECTION_CONFIG', |
| 82 | 'Could not read the existing connection configuration. It has not been replaced.' |
| 83 | ) |
| 84 | } |
| 85 | this.config = { |
| 86 | enabled: saved.enabled === true, |
| 87 | token: |
| 88 | typeof saved.token === 'string' && saved.token.length >= 32 |
| 89 | ? saved.token |
| 90 | : randomBytes(32).toString('hex'), |
| 91 | port: 0, |
| 92 | executable, |
| 93 | launchArgs, |
| 94 | profile: folder, |
| 95 | } |
| 96 | this.persist() |
| 97 | } |
| 98 | persist() { |
| 99 | const temp = `${this.file}.tmp` |
| 100 | fs.writeFileSync(temp, JSON.stringify(this.config), { mode: 0o600 }) |
| 101 | fs.chmodSync(temp, 0o600) |
| 102 | fs.renameSync(temp, this.file) |
| 103 | fs.chmodSync(this.file, 0o600) |
| 104 | } |
| 105 | async start() { |
| 106 | if (!this.config.enabled || this.server) return this.status() |
| 107 | const server = http.createServer((request, response) => { |
| 108 | this.handle(request, response).catch(() => { |
| 109 | if (!response.headersSent) this.send(response, 500, { error: 'Local connection failed.' }) |
| 110 | else response.destroy() |
| 111 | }) |
| 112 | }) |
| 113 | server.requestTimeout = 30000 |
| 114 | server.headersTimeout = 10000 |
| 115 | try { |
| 116 | await new Promise((resolve, reject) => { |
| 117 | server.once('error', reject) |
| 118 | server.listen(0, '127.0.0.1', resolve) |
| 119 | }) |
| 120 | this.server = server |
| 121 | this.config.port = server.address().port |
| 122 | this.error = '' |
| 123 | this.persist() |
| 124 | } catch (error) { |
| 125 | server.close() |
| 126 | this.error = 'Could not start the local connector. Toggle the connection to retry.' |
| 127 | throw error |
| 128 | } |
| 129 | this.changed() |
| 130 | return this.status() |
| 131 | } |
| 132 | async enable(enabled) { |
| 133 | this.config.enabled = enabled |
| 134 | if (!enabled) { |
| 135 | this.persist() |
| 136 | await this.stop() |
| 137 | } else { |
| 138 | this.persist() |
| 139 | await this.start() |
| 140 | } |
| 141 | this.changed() |
| 142 | return this.status() |
| 143 | } |
| 144 | async stop() { |
| 145 | const server = this.server |
| 146 | this.server = null |
| 147 | this.config.port = 0 |
| 148 | this.persist() |
| 149 | if (server) |
| 150 | await new Promise((resolve) => { |
| 151 | server.close(resolve) |
| 152 | server.closeAllConnections() |
| 153 | }) |
| 154 | } |
| 155 | reset() { |
| 156 | this.config.token = randomBytes(32).toString('hex') |
| 157 | this.persist() |
| 158 | this.changed() |
| 159 | return this.status() |
| 160 | } |
| 161 | status() { |
| 162 | return { |
| 163 | enabled: this.config.enabled, |
| 164 | running: !!this.server, |
| 165 | endpoint: this.server ? `http://127.0.0.1:${this.config.port}/mcp` : null, |
| 166 | error: this.error, |
| 167 | configFile: this.file, |
| 168 | } |
| 169 | } |
| 170 | configuration(transport) { |
| 171 | if (!this.config.enabled || !this.server) |
| 172 | throw new AppError('CONNECTION_DISABLED', 'Enable the connection first.') |
| 173 | if (transport === 'http') |
| 174 | return { |
| 175 | mcpServers: { |
| 176 | opentalon: { |
| 177 | type: 'http', |
| 178 | url: `http://127.0.0.1:${this.config.port}/mcp`, |
| 179 | headers: { Authorization: `Bearer ${this.config.token}` }, |
| 180 | }, |
| 181 | }, |
| 182 | } |
| 183 | return { |
| 184 | mcpServers: { |
| 185 | opentalon: { |
| 186 | command: this.stdioCommand || this.executable, |
| 187 | args: [path.join(__dirname, 'mcp-bridge.cjs')], |
| 188 | env: { |
| 189 | ...(this.stdioCommand ? {} : { ELECTRON_RUN_AS_NODE: '1' }), |
| 190 | OPENTALON_MCP_CONFIG: this.file, |
| 191 | }, |
| 192 | }, |
| 193 | }, |
| 194 | } |
| 195 | } |
| 196 | send(response, status, body) { |
| 197 | response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }) |
| 198 | response.end(body === undefined ? undefined : JSON.stringify(body)) |
| 199 | } |
| 200 | authorized(request) { |
| 201 | const actual = Buffer.from(request.headers.authorization || '') |
| 202 | const expected = Buffer.from(`Bearer ${this.config.token}`) |
| 203 | return actual.length === expected.length && timingSafeEqual(actual, expected) |
| 204 | } |
| 205 | async handle(request, response) { |
| 206 | if (!this.config.enabled || !this.server) |
| 207 | return this.send(response, 503, { error: 'Connection disabled.' }) |
| 208 | if ( |
| 209 | request.headers.origin !== undefined || |
| 210 | request.headers.host !== `127.0.0.1:${this.config.port}` |
| 211 | ) |
| 212 | return this.send(response, 403, { error: 'Only local non-browser clients are allowed.' }) |
| 213 | if (!this.authorized(request)) |
| 214 | return this.send(response, 401, { error: 'Invalid connection key.' }) |
| 215 | if (request.url !== '/mcp') return this.send(response, 404, { error: 'Unknown endpoint.' }) |
| 216 | if (request.method !== 'POST') { |
| 217 | response.setHeader('Allow', 'POST') |
| 218 | return this.send(response, 405, { error: 'Use POST. Server event streaming is not offered.' }) |
| 219 | } |
| 220 | if (!request.headers['content-type']?.startsWith('application/json')) |
| 221 | return this.send(response, 415, { error: 'Use application/json.' }) |
| 222 | if ( |
| 223 | !request.headers.accept?.includes('application/json') || |
| 224 | !request.headers.accept?.includes('text/event-stream') |
| 225 | ) |
| 226 | return this.send(response, 406, { error: 'Accept application/json and text/event-stream.' }) |
| 227 | if ( |
| 228 | request.headers['mcp-protocol-version'] && |
| 229 | !PROTOCOLS.includes(request.headers['mcp-protocol-version']) |
| 230 | ) |
| 231 | return this.send(response, 400, { error: 'Unsupported MCP protocol version.' }) |
| 232 | if (Number(request.headers['content-length'] || 0) > MAX_BODY) { |
| 233 | request.resume() |
| 234 | return this.send(response, 413, { error: 'Request exceeds 15 MB.' }) |
| 235 | } |
| 236 | const chunks = [] |
| 237 | let size = 0 |
| 238 | for await (const chunk of request) { |
| 239 | size += chunk.length |
| 240 | if (size > MAX_BODY) { |
| 241 | this.send(response, 413, { error: 'Request exceeds 15 MB.' }) |
| 242 | return |
| 243 | } |
| 244 | chunks.push(chunk) |
| 245 | } |
| 246 | let message |
| 247 | try { |
| 248 | message = JSON.parse(Buffer.concat(chunks).toString('utf8')) |
| 249 | } catch { |
| 250 | return this.send(response, 400, { |
| 251 | jsonrpc: '2.0', |
| 252 | id: null, |
| 253 | error: { code: -32700, message: 'Parse error.' }, |
| 254 | }) |
| 255 | } |
| 256 | if ( |
| 257 | !message || |
| 258 | Array.isArray(message) || |
| 259 | message.jsonrpc !== '2.0' || |
| 260 | typeof message.method !== 'string' || |
| 261 | (message.id !== undefined && typeof message.id !== 'string' && typeof message.id !== 'number') |
| 262 | ) |
| 263 | return this.send(response, 400, { |
| 264 | jsonrpc: '2.0', |
| 265 | id: null, |
| 266 | error: { code: -32600, message: 'Invalid JSON-RPC request.' }, |
| 267 | }) |
| 268 | if (message.id === undefined) return this.send(response, 202) |
| 269 | const rpcError = (code, text) => |
| 270 | this.send(response, 200, { jsonrpc: '2.0', id: message.id, error: { code, message: text } }) |
| 271 | let result |
| 272 | if (message.method === 'initialize') { |
| 273 | if (!message.params || typeof message.params.protocolVersion !== 'string') |
| 274 | return rpcError(-32602, 'protocolVersion is required.') |
| 275 | result = { |
| 276 | protocolVersion: PROTOCOLS.includes(message.params.protocolVersion) |
| 277 | ? message.params.protocolVersion |
| 278 | : PROTOCOLS[0], |
| 279 | capabilities: { tools: { listChanged: false } }, |
| 280 | serverInfo: { name: 'OpenTalon', version: this.version }, |
| 281 | instructions: |
| 282 | 'A single-person offline task manager. Read revisions before editing. Reuse requestKey for identical retries. Show destructive previews and obtain explicit confirmation before confirming. Connection credentials are never task data.', |
| 283 | } |
| 284 | } else if (message.method === 'ping') result = {} |
| 285 | else if (message.method === 'tools/list') |
| 286 | result = { |
| 287 | tools: this.toolCatalog.map(({ mutates, ...tool }) => ({ |
| 288 | ...tool, |
| 289 | annotations: { |
| 290 | readOnlyHint: !mutates, |
| 291 | destructiveHint: tool.name === 'confirm_destructive_action', |
| 292 | idempotentHint: mutates, |
| 293 | openWorldHint: false, |
| 294 | }, |
| 295 | })), |
| 296 | } |
| 297 | else if (message.method === 'tools/call') { |
| 298 | const { name, arguments: args = {} } = message.params || {} |
| 299 | try { |
| 300 | validateAction(name, args) |
| 301 | if (!this.toolCatalog.some((tool) => tool.name === name)) |
| 302 | throw new AppError('TOOL_UNAVAILABLE', 'This tool is unavailable in this connection.') |
| 303 | const value = await this.call(name, args) |
| 304 | result = { |
| 305 | content: |
| 306 | name === 'read_comment_image' |
| 307 | ? [{ type: 'image', mimeType: value.mimeType, data: value.data }] |
| 308 | : [{ type: 'text', text: JSON.stringify(value) }], |
| 309 | structuredContent: |
| 310 | name === 'read_comment_image' |
| 311 | ? { id: value.id, name: value.name, mimeType: value.mimeType } |
| 312 | : value, |
| 313 | } |
| 314 | } catch (error) { |
| 315 | const value = errorView(error, name) |
| 316 | result = { |
| 317 | isError: true, |
| 318 | content: [{ type: 'text', text: JSON.stringify(value) }], |
| 319 | structuredContent: value, |
| 320 | } |
| 321 | } |
| 322 | } else return rpcError(-32601, 'Method not found.') |
| 323 | return this.send(response, 200, { jsonrpc: '2.0', id: message.id, result }) |
| 324 | } |
| 325 | } |
| 326 | module.exports = { Connector, errorView } |