host: tool servers (MCP) set up for the model are connected to the agent, secrets only through the environment
This commit is contained in:
1 parent
37cab2c76f
commit
1e73f53160
5 files changed
+90
-4
No files matched your search
@@ -47,6 +47,31 @@ export const modeOf = value => (Object.hasOwn(MODE_PRESETS, value) ? value : DEF
|
||||
/** The approval gate plugin (plain ESM, loaded by absolute path). */
|
||||
export const GATE_PLUGIN = fileURLToPath(new URL('./plugins/strata-gate.mjs', import.meta.url));
|
||||
|
||||
/**
|
||||
* The tool servers (MCP) set up for the model in Settings, as Harness client rows. Their tools appear to the agent as
|
||||
* `mcp__<server>__<tool>`. A command or URL goes into the patch as text; a secret (an env value or a header) never does: the row
|
||||
* carries `!!js process.env.<NAME>` and the value travels in the agent process's environment (returned in `env`).
|
||||
*/
|
||||
export function mcpRows(servers, env) {
|
||||
const rows = [];
|
||||
let index = 0;
|
||||
for (const [name, server] of Object.entries(servers ?? {})) {
|
||||
if (!server || server.disabled === true || !/^[A-Za-z0-9_-]{1,32}$/.test(name)) continue;
|
||||
const token = (kind, key, value) => {
|
||||
const variable = `STRATA_MCP_${index}_${kind}_${slug(key).replace(/-/g, '_').toUpperCase()}`;
|
||||
env[variable] = String(value);
|
||||
return `@@JS:process.env.${variable}@@`;
|
||||
};
|
||||
const config = { serverName: name, ...(server.command
|
||||
? { transport: 'stdio', command: String(server.command), args: Array.isArray(server.args) ? server.args.map(String) : [], ...(server.cwd ? { cwd: String(server.cwd) } : {}),
|
||||
...(server.env && Object.keys(server.env).length ? { env: Object.fromEntries(Object.entries(server.env).map(([k, v]) => [k, token('E', k, v)])) } : {}) }
|
||||
: { transport: 'streamable-http', url: String(server.url), ...(server.headers && Object.keys(server.headers).length ? { headers: Object.fromEntries(Object.entries(server.headers).map(([k, v]) => [k, token('H', k, v)])) } : {}) }) };
|
||||
rows.push({ id: `mcp-${slug(name)}`, name: '@deepseek-ai/dsh-mcp-client', config });
|
||||
index += 1;
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
const slug = value => String(value).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 24) || 'x';
|
||||
|
||||
/** Identity of one route's wire configuration, secret included by hash only. */
|
||||
@@ -71,6 +96,7 @@ export function buildProfile({ local = [], connections = [], gate = true }) {
|
||||
const providers = {};
|
||||
const env = {};
|
||||
const routes = [];
|
||||
const mcpEnv = {};
|
||||
// Helper agents run at most as many at once as the engine has request slots (a local model); API models take the Harness's own limit.
|
||||
let slots = 0;
|
||||
|
||||
@@ -120,6 +146,9 @@ export function buildProfile({ local = [], connections = [], gate = true }) {
|
||||
});
|
||||
|
||||
const defaultRoute = routes.find(r => r.kind === 'local') ?? null;
|
||||
// One Harness, one set of tool servers: the default local model's.
|
||||
const mcp = mcpRows(local[0]?.mcpServers, mcpEnv);
|
||||
Object.assign(env, mcpEnv);
|
||||
const entries = [
|
||||
...(defaultRoute ? [{ id: 'agent-default-model', name: '@deepseek-ai/dsh-agent-default-model', config: { provider: defaultRoute.route, model: defaultRoute.modelId } }] : []),
|
||||
{ id: 'llm-pi-ai', name: '@deepseek-ai/dsh-llm-pi-ai', config: { providers } },
|
||||
@@ -128,6 +157,7 @@ export function buildProfile({ local = [], connections = [], gate = true }) {
|
||||
{ id: 'subagent', config: { maxActiveSubagents: slots > 0 ? slots : DEFAULT_API_HELPERS } },
|
||||
// Manual asks before a change runs, so the person sees one Approve/Deny card and nothing has happened yet.
|
||||
...(gate ? [{ insert: [{ id: 'strata-gate', name: GATE_PLUGIN }] }] : []),
|
||||
...(mcp.length ? [{ insert: mcp }] : []),
|
||||
// The reminder tools would be a second scheduler beside the app's Tasks; web search needs a search-service key the app has none of.
|
||||
{ id: 'preset-standard', name: '@deepseek-ai/dsh-agent-preset', config: standardPreset() },
|
||||
// Strata names its chats itself; the Harness's own title request would be an extra model call on
|
||||
@@ -135,7 +165,9 @@ export function buildProfile({ local = [], connections = [], gate = true }) {
|
||||
{ id: 'session-title-llm', disabled: true },
|
||||
];
|
||||
// JSON is valid YAML, and a JSON document cannot be mis-quoted by a model id or a display name.
|
||||
const patch = `# Generated by the Strata host. Contains credential NAMES only, never values.\n${JSON.stringify(entries, null, 2)}\n`;
|
||||
// JSON is valid YAML. A tool server's secret is a `!!js process.env.NAME` value, swapped in after stringifying.
|
||||
const json = JSON.stringify(entries, null, 2).replace(/"@@JS:([A-Za-z0-9_.]+)@@"/g, '!!js $1');
|
||||
const patch = `# Generated by the Strata host. Contains credential NAMES only, never values.\n${json}\n`;
|
||||
// The signature decides whether the running agent must be restarted. It covers the secret values
|
||||
// through a hash so a changed key is noticed, and the hash is never reversible into the key.
|
||||
const signature = createHash('sha256').update(patch).update(JSON.stringify(Object.entries(env).sort())).digest('hex').slice(0, 16);
|
||||
|
||||
@@ -94,6 +94,8 @@ const agent = createAgentBridge({
|
||||
context: i.metrics?.engine?.max_context ?? i.context ?? undefined, key: i.key, vision: i.vision,
|
||||
// The engine's request slots: helper agents never outnumber them.
|
||||
slots: i.metrics?.live?.slots?.length || i.parallel || 1,
|
||||
// The tool servers set up for this model (Settings, Tools): the agent connects to the same ones.
|
||||
mcpServers: i.mcpServers,
|
||||
})),
|
||||
connections: () => modelProviders.withSecrets(),
|
||||
log: line => console.log(line),
|
||||
|
||||
@@ -33,7 +33,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
let defaultId=null,timer=null,closing=false,polling=false;
|
||||
const emit=()=>{const value=state();writeFileSync(join(directory,'native-jobs.json'),JSON.stringify(value.jobs),{mode:0o600});changed(value);};
|
||||
const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();};
|
||||
function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),calibration:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};}
|
||||
function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,mcpServers,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),calibration:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};}
|
||||
function sourceText(){try{return readFileSync(join(packaged?control.control.dir:preferences.repo,'serve/server.py'),'utf8');}catch{return '';}}
|
||||
function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));}
|
||||
function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};}
|
||||
@@ -118,7 +118,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
if(!args.multiple){if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish or cancel native requests before switching models.');for(const id of [...instances.keys()])await unload(id);}else if(matching)await unload(matching.id);
|
||||
if(job.state!=='running')return;
|
||||
writeFileSync(configPath,JSON.stringify(cfg,null,2),{mode:0o600});
|
||||
const instance={id,apiModelId,fingerprint,context:entry.context??0,aliases:cfg.aliases??[],vision:!!cfg.vision,model:args.model,label:entry.model_name??args.model,port:cfg.port,gpus:Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu],status:'loading',phase:'loading',parallel:cfg.parallel??1,key,configPath,loadedAt:new Date().toISOString(),metrics:null,error:null};
|
||||
const instance={id,apiModelId,fingerprint,context:entry.context??0,aliases:cfg.aliases??[],vision:!!cfg.vision,model:args.model,label:entry.model_name??args.model,port:cfg.port,gpus:Array.isArray(cfg.gpu)?cfg.gpu:cfg.gpu===undefined?[]:[cfg.gpu],status:'loading',phase:'loading',parallel:cfg.parallel??1,mcpServers:cfg.mcp_servers??cfg.mcpServers??{},key,configPath,loadedAt:new Date().toISOString(),metrics:null,error:null};
|
||||
let proc=null,started=null;
|
||||
if(packaged){
|
||||
/* The engine starts under Control's owner runtime, not as our child: a saved profile per slot, then `runtime start`. */
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
*/
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { startScriptedWorker } from './helpers/scripted-worker.mjs';
|
||||
@@ -186,3 +186,37 @@ test('Manual refuses to start when the gate is not loaded (it would be an open s
|
||||
t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });
|
||||
await assert.rejects(bridge.runTurn({ chatId: 'x', message: 'SCRIPT:echo hi', workspacePath: join(dir, 'ws'), mode: 'manual', onFrame: () => {} }), error => error.code === 'mode-unavailable' && /asks before changing/.test(error.message) && !/sandbox/i.test(error.message));
|
||||
});
|
||||
|
||||
test('a tool server set up for the model is connected to the agent: its tools are offered, Manual asks before using them, and its secret never reaches a file', { skip }, async (t) => {
|
||||
const worker = await startScriptedWorker({});
|
||||
const dir = mkdtempSync(join(tmpdir(), 'strata-mcp-'));
|
||||
const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
|
||||
const mcpServers = { demo: { command: process.execPath, args: [fwd(join(import.meta.dirname, 'helpers', 'mini-mcp.mjs'))], env: { DEMO_TOKEN: 'tok-123456-secret' } }, off: { command: 'x', disabled: true } };
|
||||
const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 2, mcpServers }];
|
||||
const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 });
|
||||
t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });
|
||||
const frames = [];
|
||||
await bridge.runTurn({ chatId: 'mcp-bypass', message: `SCRIPT:call mcp__demo__shout ${JSON.stringify({ text: 'hello' })}`, workspacePath: ws, mode: 'bypass', onFrame: f => frames.push(f) });
|
||||
assert.ok([...worker.requests].reverse().find(q => q.toolNames.length).toolNames.includes('mcp__demo__shout'));
|
||||
assert.ok(![...worker.requests].some(q => q.toolNames.some(n => n.startsWith('mcp__off'))), 'a disabled server is not connected');
|
||||
const card = cards(frames).at(-1);
|
||||
assert.equal(card.state, 'done'); assert.match(card.result, /HELLO\|token:set/, 'the secret reached the server through the environment');
|
||||
assert.equal(card.scope, 'connected');
|
||||
// Manual: a connected tool has unknown effects, so it asks first
|
||||
const manual = [];
|
||||
await bridge.runTurn({
|
||||
chatId: 'mcp-manual', message: `SCRIPT:call mcp__demo__shout ${JSON.stringify({ text: 'ask me' })}`, workspacePath: ws, mode: 'manual',
|
||||
onFrame: f => { manual.push(f); if (f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId: 'mcp-manual', callId: f.tool.id, decision: 'approve' }); },
|
||||
});
|
||||
assert.deepEqual(cards(manual).map(c => c.state), ['running', 'proposed', 'running', 'done']);
|
||||
assert.match(cards(manual)[1].effect, /Use the connected tool demo \/ shout/);
|
||||
// the secret is in the environment of the agent only: never in the profile file
|
||||
const files = JSON.stringify(readdirDeep(join(dir, 'agent')).filter(f => f.endsWith('.yml')).map(f => readFileSync(f, 'utf8')));
|
||||
assert.ok(files.includes('process.env.STRATA_MCP_0_E_DEMO_TOKEN') && !files.includes('tok-123456-secret'));
|
||||
});
|
||||
|
||||
function readdirDeep(dir) {
|
||||
const out = [];
|
||||
for (const e of readdirSync(dir, { withFileTypes: true })) { const p = join(dir, e.name); if (e.isDirectory()) out.push(...readdirDeep(p)); else out.push(p); }
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// A minimal MCP server over stdio (newline-delimited JSON-RPC), for the tool-server test. One tool, `shout`: it upper-cases
|
||||
// its text and reports whether the secret from the environment arrived, WITHOUT printing the secret.
|
||||
import { createInterface } from 'node:readline';
|
||||
|
||||
const send = message => process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`);
|
||||
createInterface({ input: process.stdin }).on('line', line => {
|
||||
let m; try { m = JSON.parse(line); } catch { return; }
|
||||
if (m.method === 'initialize') {
|
||||
send({ id: m.id, result: { protocolVersion: m.params?.protocolVersion ?? '2025-06-18', capabilities: { tools: { listChanged: false } }, serverInfo: { name: 'mini', version: '1.0.0' } } });
|
||||
} else if (m.method === 'tools/list') {
|
||||
send({ id: m.id, result: { tools: [{ name: 'shout', description: 'Upper-case the text.', inputSchema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'] } }] } });
|
||||
} else if (m.method === 'tools/call') {
|
||||
const text = String(m.params?.arguments?.text ?? '');
|
||||
send({ id: m.id, result: { content: [{ type: 'text', text: `${text.toUpperCase()}|token:${process.env.DEMO_TOKEN ? 'set' : 'missing'}` }] } });
|
||||
} else if (m.id !== undefined && m.method) {
|
||||
send({ id: m.id, result: {} });
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user