import { describe, it, expect, beforeAll } from 'vitest'; import { pool } from '../../lib/db/pool.js'; import { resetDb } from '../helpers/db.js'; import { migrateUp } from '../../lib/db/migrate.js'; import * as agentsRepo from '../../lib/db/repos/agents.js'; import { buildCtxFromAgent } from '../../lib/mcp/context.js'; import { listExternalTools, callExternalTool } from '../../lib/mcp/http.js'; let spaceId, otherSpace, pageInOther, agent; const owner = { kind: 'user', id: null }; beforeAll(async () => { await resetDb(); await migrateUp(); ({ rows: [{ id: spaceId }] } = await pool.query(`INSERT INTO spaces(slug,name) VALUES('s','S') RETURNING id`)); ({ rows: [{ id: otherSpace }] } = await pool.query(`INSERT INTO spaces(slug,name) VALUES('o','O') RETURNING id`)); ({ rows: [{ id: pageInOther }] } = await pool.query( `INSERT INTO pages(space_id,slug,title,body_md) VALUES($1,'sec','Secret','hidden') RETURNING id`, [otherSpace])); agent = await agentsRepo.create({ slug: `ext-${Date.now()}`, name: 'Ext', kind: 'claude', model: 'sonnet', capabilities: { read: true, suggest: true }, scopes: { space_id: spaceId } }, owner); }); describe('external registry', () => { it('exposes exactly the four read+suggest tools', () => { const names = listExternalTools().map(t => t.name).sort(); expect(names).toEqual(['context', 'propose_change', 'read', 'search']); }); it('buildCtxFromAgent forces the agent bound space + spaceScoped', () => { const ctx = buildCtxFromAgent(agent); expect(ctx.space_id).toBe(spaceId); expect(ctx.spaceScoped).toBe(true); expect(ctx.agent.id).toBe(agent.id); }); it('read cannot reach another space', async () => { const ctx = buildCtxFromAgent(agent); const out = await callExternalTool('read', { kind: 'page', id: pageInOther }, ctx); expect(out.error).toMatch(/not found/i); }); it('propose_change lands in pending_changes with agent + space, applied:false', async () => { const ctx = buildCtxFromAgent(agent); const out = await callExternalTool('propose_change', { entity_type: 'page', action: 'create', payload: { slug: 'np', title: 'New', body_md: 'b' }, reason: 'r' }, ctx); expect(out.applied).toBe(false); expect(out.pending_change_id).toBeTruthy(); const { rows: [pc] } = await pool.query(`SELECT * FROM pending_changes WHERE id=$1`, [out.pending_change_id]); expect(pc.agent_id).toBe(agent.id); expect(pc.payload.space_id).toBe(spaceId); }); it('unknown tool throws', async () => { await expect(callExternalTool('nope', {}, buildCtxFromAgent(agent))).rejects.toThrow(/unknown tool/i); }); });