|
| 1 | +/* |
| 2 | + * client_adapter.c — Generate client extension modules from the MCP tool registry. |
| 3 | + * |
| 4 | + * See client_adapter.h for why these are generated rather than shipped. |
| 5 | + */ |
| 6 | +#include "cli/client_adapter.h" |
| 7 | + |
| 8 | +#include "foundation/constants.h" |
| 9 | +#include "mcp/mcp.h" |
| 10 | + |
| 11 | +#include <stdbool.h> |
| 12 | +#include <stdio.h> |
| 13 | +#include <stdlib.h> |
| 14 | +#include <string.h> |
| 15 | + |
| 16 | +/* A generated module is small and bounded by the registry size; grow a plain |
| 17 | + * buffer rather than pulling in a builder for two call sites. */ |
| 18 | +typedef struct { |
| 19 | + char *buf; |
| 20 | + size_t len; |
| 21 | + size_t cap; |
| 22 | + bool failed; |
| 23 | +} adapter_sb_t; |
| 24 | + |
| 25 | +static void sb_append(adapter_sb_t *sb, const char *s) { |
| 26 | + if (sb->failed || !s) { |
| 27 | + return; |
| 28 | + } |
| 29 | + size_t add = strlen(s); |
| 30 | + if (sb->len + add + 1 > sb->cap) { |
| 31 | + size_t want = sb->cap ? sb->cap : CBM_SZ_2K; |
| 32 | + while (want < sb->len + add + 1) { |
| 33 | + if (want > SIZE_MAX / PAIR_LEN) { |
| 34 | + sb->failed = true; |
| 35 | + return; |
| 36 | + } |
| 37 | + want *= PAIR_LEN; |
| 38 | + } |
| 39 | + char *grown = realloc(sb->buf, want); |
| 40 | + if (!grown) { |
| 41 | + sb->failed = true; |
| 42 | + return; |
| 43 | + } |
| 44 | + sb->buf = grown; |
| 45 | + sb->cap = want; |
| 46 | + } |
| 47 | + memcpy(sb->buf + sb->len, s, add); |
| 48 | + sb->len += add; |
| 49 | + sb->buf[sb->len] = '\0'; |
| 50 | +} |
| 51 | + |
| 52 | +bool cbm_client_adapter_escape_js(const char *in, char *out, size_t out_sz) { |
| 53 | + if (!in || !out || out_sz == 0) { |
| 54 | + return false; |
| 55 | + } |
| 56 | + size_t o = 0; |
| 57 | + for (const char *p = in; *p; p++) { |
| 58 | + /* Only these four can terminate or corrupt a single-quoted literal. |
| 59 | + * Escaping more would be harmless but makes the emitted path harder to |
| 60 | + * read when a user opens the generated file. */ |
| 61 | + const char *esc = NULL; |
| 62 | + switch (*p) { |
| 63 | + case '\\': |
| 64 | + esc = "\\\\"; |
| 65 | + break; |
| 66 | + case '\'': |
| 67 | + esc = "\\'"; |
| 68 | + break; |
| 69 | + case '\n': |
| 70 | + esc = "\\n"; |
| 71 | + break; |
| 72 | + case '\r': |
| 73 | + esc = "\\r"; |
| 74 | + break; |
| 75 | + default: |
| 76 | + break; |
| 77 | + } |
| 78 | + size_t need = esc ? strlen(esc) : 1U; |
| 79 | + if (o + need + 1 > out_sz) { |
| 80 | + out[0] = '\0'; |
| 81 | + return false; /* never emit a truncated literal */ |
| 82 | + } |
| 83 | + if (esc) { |
| 84 | + memcpy(out + o, esc, need); |
| 85 | + } else { |
| 86 | + out[o] = *p; |
| 87 | + } |
| 88 | + o += need; |
| 89 | + } |
| 90 | + out[o] = '\0'; |
| 91 | + return true; |
| 92 | +} |
| 93 | + |
| 94 | +/* Shared preamble: the ownership markers and a note telling whoever opens the |
| 95 | + * file that edits inside the block are overwritten. */ |
| 96 | +static void emit_header(adapter_sb_t *sb, const char *client) { |
| 97 | + /* No markers here: cbm_text_upsert_managed_block adds them and REJECTS |
| 98 | + * content that already carries them, so the body must stay marker-free. */ |
| 99 | + sb_append(sb, "// Generated by codebase-memory-mcp for "); |
| 100 | + sb_append(sb, client); |
| 101 | + sb_append(sb, |
| 102 | + ".\n" |
| 103 | + "// Regenerated on install/update from the MCP tool registry, so it cannot\n" |
| 104 | + "// drift from the tools the server actually serves. Edits inside this block\n" |
| 105 | + "// are overwritten; edit outside it, or remove the markers to take ownership.\n"); |
| 106 | +} |
| 107 | + |
| 108 | +char *cbm_client_adapter_pi(const char *binary_path) { |
| 109 | + if (!binary_path || !binary_path[0]) { |
| 110 | + return NULL; |
| 111 | + } |
| 112 | + char bin[CBM_SZ_1K]; |
| 113 | + if (!cbm_client_adapter_escape_js(binary_path, bin, sizeof(bin))) { |
| 114 | + return NULL; |
| 115 | + } |
| 116 | + int count = cbm_mcp_tool_count(); |
| 117 | + if (count <= 0) { |
| 118 | + return NULL; |
| 119 | + } |
| 120 | + |
| 121 | + adapter_sb_t sb = {0}; |
| 122 | + emit_header(&sb, "pi"); |
| 123 | + sb_append(&sb, "import { spawn } from 'node:child_process';\n\n"); |
| 124 | + sb_append(&sb, "const BIN = '"); |
| 125 | + sb_append(&sb, bin); |
| 126 | + sb_append(&sb, "';\n\n"); |
| 127 | + |
| 128 | + /* One shared invoker: the binary prints JSON on stdout, so take the last |
| 129 | + * line that parses rather than trusting the first — a stray log line on |
| 130 | + * stdout must not break the bridge. */ |
| 131 | + sb_append( |
| 132 | + &sb, "async function call(tool, args, signal) {\n" |
| 133 | + " return new Promise((resolve) => {\n" |
| 134 | + " const child = spawn(BIN, ['cli', tool, JSON.stringify(args ?? {})], {\n" |
| 135 | + " stdio: ['ignore', 'pipe', 'pipe'],\n" |
| 136 | + " env: { ...process.env, CBM_LOG_LEVEL: 'error' },\n" |
| 137 | + " });\n" |
| 138 | + " let out = '';\n" |
| 139 | + " const onAbort = () => { if (!child.killed) child.kill(); };\n" |
| 140 | + " signal?.addEventListener('abort', onAbort, { once: true });\n" |
| 141 | + " child.stdout.on('data', (d) => (out += d.toString()));\n" |
| 142 | + " child.on('error', (e) => {\n" |
| 143 | + " signal?.removeEventListener('abort', onAbort);\n" |
| 144 | + " resolve({ error: String(e && e.message ? e.message : e) });\n" |
| 145 | + " });\n" |
| 146 | + " child.on('close', () => {\n" |
| 147 | + " signal?.removeEventListener('abort', onAbort);\n" |
| 148 | + " const lines = out.split('\\n').map((l) => l.trim()).filter(Boolean);\n" |
| 149 | + " for (let i = lines.length - 1; i >= 0; i--) {\n" |
| 150 | + " try { return resolve(JSON.parse(lines[i])); } catch { /* keep scanning */ }\n" |
| 151 | + " }\n" |
| 152 | + " resolve({ error: 'no JSON response from codebase-memory-mcp' });\n" |
| 153 | + " });\n" |
| 154 | + " });\n" |
| 155 | + "}\n\n"); |
| 156 | + |
| 157 | + /* Register every tool the registry advertises — never a hand-picked subset, |
| 158 | + * which is the drift this generator exists to prevent. */ |
| 159 | + sb_append(&sb, "export function register(pi) {\n"); |
| 160 | + for (int i = 0; i < count; i++) { |
| 161 | + const char *name = cbm_mcp_tool_name(i); |
| 162 | + if (!name || !name[0]) { |
| 163 | + continue; |
| 164 | + } |
| 165 | + sb_append(&sb, " pi.registerTool({ name: '"); |
| 166 | + sb_append(&sb, name); |
| 167 | + sb_append(&sb, "', run: (args, ctx) => call('"); |
| 168 | + sb_append(&sb, name); |
| 169 | + sb_append(&sb, "', args, ctx?.signal) });\n"); |
| 170 | + } |
| 171 | + sb_append(&sb, "}\n"); |
| 172 | + |
| 173 | + if (sb.failed) { |
| 174 | + free(sb.buf); |
| 175 | + return NULL; |
| 176 | + } |
| 177 | + return sb.buf; |
| 178 | +} |
| 179 | + |
| 180 | +char *cbm_client_adapter_opencode(const char *binary_path) { |
| 181 | + if (!binary_path || !binary_path[0]) { |
| 182 | + return NULL; |
| 183 | + } |
| 184 | + char bin[CBM_SZ_1K]; |
| 185 | + if (!cbm_client_adapter_escape_js(binary_path, bin, sizeof(bin))) { |
| 186 | + return NULL; |
| 187 | + } |
| 188 | + |
| 189 | + adapter_sb_t sb = {0}; |
| 190 | + emit_header(&sb, "OpenCode"); |
| 191 | + sb_append(&sb, "// OpenCode already reaches every tool over MCP; this adds only the\n" |
| 192 | + "// automatic graph lookup before a grep/glob, which other clients get\n" |
| 193 | + "// through their own hook configuration.\n"); |
| 194 | + sb_append(&sb, "import { spawn } from 'node:child_process';\n\n"); |
| 195 | + sb_append(&sb, "const BIN = '"); |
| 196 | + sb_append(&sb, bin); |
| 197 | + sb_append(&sb, "';\n\n"); |
| 198 | + |
| 199 | + /* hook-augment requires hook_event_name and accepts Grep/Glob only under |
| 200 | + * PreToolUse; omitting it makes the whole hook a silent no-op. */ |
| 201 | + sb_append(&sb, "function augment(tool, args) {\n" |
| 202 | + " return new Promise((resolve) => {\n" |
| 203 | + " const child = spawn(BIN, ['hook-augment'], {\n" |
| 204 | + " stdio: ['pipe', 'pipe', 'ignore'],\n" |
| 205 | + " env: { ...process.env, CBM_LOG_LEVEL: 'error' },\n" |
| 206 | + " });\n" |
| 207 | + " let out = '';\n" |
| 208 | + " child.stdout.on('data', (d) => (out += d.toString()));\n" |
| 209 | + " child.on('error', () => resolve(''));\n" |
| 210 | + " child.on('close', () => resolve(out));\n" |
| 211 | + " child.stdin.end(JSON.stringify({\n" |
| 212 | + " hook_event_name: 'PreToolUse',\n" |
| 213 | + " tool_name: tool,\n" |
| 214 | + " tool_input: args ?? {},\n" |
| 215 | + " }));\n" |
| 216 | + " });\n" |
| 217 | + "}\n\n"); |
| 218 | + |
| 219 | + sb_append(&sb, |
| 220 | + "export const CodebaseMemory = async () => ({\n" |
| 221 | + " 'tool.execute.after': async (input, output) => {\n" |
| 222 | + " const tool = input?.tool === 'grep' ? 'Grep' : input?.tool === 'glob' ? 'Glob' " |
| 223 | + ": null;\n" |
| 224 | + " if (!tool) return;\n" |
| 225 | + " const extra = await augment(tool, output?.args);\n" |
| 226 | + " if (extra && typeof output?.output === 'string') {\n" |
| 227 | + " output.output += '\\n' + extra;\n" |
| 228 | + " }\n" |
| 229 | + " },\n" |
| 230 | + "});\n"); |
| 231 | + |
| 232 | + if (sb.failed) { |
| 233 | + free(sb.buf); |
| 234 | + return NULL; |
| 235 | + } |
| 236 | + return sb.buf; |
| 237 | +} |
0 commit comments