feat(engine): add private NDC nodes and ontology bridge

This commit is contained in:
Codex
2026-07-16 02:23:45 +03:00
parent 569b8762e6
commit 59e9c92415
25 changed files with 10450 additions and 12 deletions
+2 -1
View File
@@ -5,7 +5,8 @@
"type": "module",
"scripts": {
"start": "node src/server.mjs",
"dev": "node --watch src/server.mjs"
"dev": "node --watch src/server.mjs",
"smoke:ontology-mcp-proxy": "node src/scripts/smoke-ontology-mcp-proxy.mjs"
},
"dependencies": {
"express": "^5.2.1",
@@ -0,0 +1,129 @@
#!/usr/bin/env node
import assert from 'node:assert/strict'
import { spawn } from 'node:child_process'
import { once } from 'node:events'
import { createServer } from 'node:http'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { WebSocket } from 'ws'
import { createOntologyMcpServer } from '../../../ontology-core/src/mcp-server.mjs'
const INTERNAL_TOKEN = 'hub-ontology-mcp-smoke-token'
const PAIRING_CODE = 'ONTOLOGYSMOKE1'
const currentFile = fileURLToPath(import.meta.url)
const hubRoot = path.resolve(path.dirname(currentFile), '..', '..')
const ontologyPort = await availablePort()
const hubPort = await availablePort()
const ontologyServer = createOntologyMcpServer({
internalTokens: [INTERNAL_TOKEN],
allowedOrigins: [],
maxBodyBytes: 1024 * 1024,
})
const hubProcess = spawn(process.execPath, ['src/server.mjs'], {
cwd: hubRoot,
env: {
...process.env,
PORT: String(hubPort),
AI_WORKSPACE_HUB_TOKEN: INTERNAL_TOKEN,
NODEDC_INTERNAL_ACCESS_TOKEN: INTERNAL_TOKEN,
NODEDC_ONTOLOGY_CORE_URL: `http://127.0.0.1:${ontologyPort}`,
NODEDC_AI_WORKSPACE_ASSISTANT_URL: 'http://127.0.0.1:1',
},
stdio: ['ignore', 'pipe', 'pipe'],
})
let hubOutput = ''
hubProcess.stdout.on('data', (chunk) => { hubOutput += String(chunk) })
hubProcess.stderr.on('data', (chunk) => { hubOutput += String(chunk) })
let worker = null
try {
await new Promise((resolve) => ontologyServer.listen(ontologyPort, '127.0.0.1', resolve))
await waitForHub(`http://127.0.0.1:${hubPort}/healthz`, hubProcess)
worker = new WebSocket(
`ws://127.0.0.1:${hubPort}/api/ai-workspace/hub?pairingCode=${PAIRING_CODE}&machineName=ontology-smoke`,
)
await once(worker, 'open')
worker.send(JSON.stringify({
type: 'hello',
agentVersion: 'smoke',
protocolVersion: 'ai-workspace-bridge/v1',
capabilities: ['smoke'],
}))
const response = await fetch(
`http://127.0.0.1:${hubPort}/api/ai-workspace/hub/v1/ontology-mcp/${PAIRING_CODE}/mcp`,
{
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json, text/event-stream',
'mcp-protocol-version': '2025-06-18',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: {
name: 'ontology_get_entity',
arguments: { term: 'helius' },
},
}),
},
)
const payload = await response.json()
assert.equal(response.ok, true)
assert.equal(response.headers.get('mcp-protocol-version'), '2025-06-18')
assert.equal(payload.result.structuredContent.entity.id, 'gelios.integration')
worker.close()
await once(worker, 'close')
const offline = await fetch(
`http://127.0.0.1:${hubPort}/api/ai-workspace/hub/v1/ontology-mcp/${PAIRING_CODE}/mcp`,
{ method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' },
)
assert.equal(offline.status, 503)
console.log(JSON.stringify({
ok: true,
checks: [
'pairing_bound_hub_proxy',
'internal_bearer_replaced_by_hub',
'ontology_mcp_tool_response',
'mcp_protocol_header_forwarded',
'offline_pairing_is_rejected',
],
}, null, 2))
} finally {
if (worker && worker.readyState === WebSocket.OPEN) worker.close()
if (hubProcess.exitCode === null && !hubProcess.killed) {
hubProcess.kill('SIGTERM')
await once(hubProcess, 'exit').catch(() => {})
}
await new Promise((resolve, reject) => ontologyServer.close((error) => error ? reject(error) : resolve()))
if (hubProcess.exitCode && hubProcess.exitCode !== 0) {
throw new Error(`hub_smoke_child_failed:${hubOutput.slice(-2000)}`)
}
}
async function availablePort() {
const server = createServer()
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const port = server.address().port
await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()))
return port
}
async function waitForHub(url, processRef) {
for (let attempt = 0; attempt < 40; attempt += 1) {
if (processRef.exitCode !== null) throw new Error('hub_smoke_child_exited_early')
try {
const response = await fetch(url)
if (response.ok) return
} catch {}
await new Promise((resolve) => setTimeout(resolve, 100))
}
throw new Error('hub_smoke_health_timeout')
}
+63
View File
@@ -34,6 +34,7 @@ app.get("/healthz", (_req, res) => {
agentsOnline: Array.from(agentsByCode.values()).filter(isAgentOnline).length,
assistantRelays: assistantRelaysById.size,
internalApiConfigured: config.internalAccessTokens.length > 0,
ontologyMcpProxyConfigured: Boolean(config.ontologyCoreUrl && config.ontologyCoreAccessToken),
});
});
@@ -85,6 +86,7 @@ app.post("/api/ai-workspace/hub/v1/assistant-relays/:relayId/poll", requireInter
app.post("/api/ai-workspace/hub/v1/assistant-relays/:relayId/results/:callId", requireInternalApi, asyncRoute(completeAssistantRelayCall));
app.use("/api/ai-workspace/hub/v1/ndc-agent-mcp/:pairingCode", asyncRoute(proxyNdcAgentMcp));
app.use("/api/ai-workspace/hub/v1/ontology-mcp/:pairingCode", asyncRoute(proxyOntologyMcp));
app.use((error, _req, res, _next) => {
const status = Number(error?.status || 500);
@@ -288,6 +290,60 @@ async function proxyNdcAgentMcp(req, res) {
res.send(text);
}
async function proxyOntologyMcp(req, res) {
if (!config.ontologyCoreUrl || !config.ontologyCoreAccessToken) {
res.status(503).json({ ok: false, error: "ontology_mcp_proxy_not_configured" });
return;
}
const pairingCode = cleanPairingCode(req.params.pairingCode);
const agent = agentsByCode.get(pairingCode);
if (!agent || !isAgentOnline(agent)) {
res.status(503).json({ ok: false, error: "bridge_agent_offline" });
return;
}
const marker = `/api/ai-workspace/hub/v1/ontology-mcp/${encodeURIComponent(req.params.pairingCode)}`;
const suffix = String(req.originalUrl || "").startsWith(marker)
? String(req.originalUrl || "").slice(marker.length)
: String(req.url || "");
const targetUrl = `${config.ontologyCoreUrl.replace(/\/+$/, "")}${suffix || "/mcp"}`;
await proxyInternalMcpRequest(req, res, targetUrl, config.ontologyCoreAccessToken);
}
async function proxyInternalMcpRequest(req, res, targetUrl, accessToken) {
const method = String(req.method || "GET").toUpperCase();
const hasBody = !["GET", "HEAD"].includes(method);
const upstream = await fetch(targetUrl, {
method,
redirect: "manual",
headers: {
Accept: String(req.headers.accept || "application/json, text/event-stream"),
Authorization: `Bearer ${accessToken}`,
...forwardMcpHeaders(req),
...(hasBody ? { "Content-Type": "application/json" } : {}),
},
...(hasBody ? { body: JSON.stringify(req.body || {}) } : {}),
});
const contentType = upstream.headers.get("content-type") || "application/json; charset=utf-8";
const text = await upstream.text();
res.status(upstream.status);
res.setHeader("content-type", contentType);
for (const header of ["cache-control", "mcp-protocol-version", "mcp-session-id", "vary"]) {
const value = upstream.headers.get(header);
if (value) res.setHeader(header, value);
}
res.send(text);
}
function forwardMcpHeaders(req) {
const headers = {};
for (const name of ["mcp-protocol-version", "mcp-session-id", "last-event-id"]) {
const value = cleanString(req.headers[name], 1000);
if (value) headers[name] = value;
}
return headers;
}
async function proxyAssistantActions(req, res) {
if (!config.assistantInternalUrl || !config.assistantInternalAccessToken) {
res.status(503).json({ ok: false, error: "assistant_action_proxy_not_configured" });
@@ -793,6 +849,13 @@ function readConfig() {
1000,
).replace(/\/+$/, ""),
assistantInternalAccessToken: cleanString(process.env.NODEDC_INTERNAL_ACCESS_TOKEN, 1000),
ontologyCoreUrl: cleanString(
process.env.NODEDC_ONTOLOGY_CORE_URL ||
process.env.NDC_ONTOLOGY_CORE_URL ||
"http://ontology-core:18104",
1000,
).replace(/\/+$/, ""),
ontologyCoreAccessToken: cleanString(process.env.NODEDC_INTERNAL_ACCESS_TOKEN, 1000),
};
}