Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,148 @@
|
||||
import { type Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { type JSONRPCMessage, JSONRPCMessageSchema } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
const mcpTransportLogger = createScopedLogger("mcp.fetch-transport");
|
||||
|
||||
/**
|
||||
* Server transport for SSE using Standard Fetch: this will send messages over
|
||||
* an SSE connection and receive messages from HTTP POST requests.
|
||||
*/
|
||||
export class FetchSSEServerTransport implements Transport {
|
||||
#stream?: ReadableStreamDefaultController<string>;
|
||||
#sessionId: string;
|
||||
#endpoint: string;
|
||||
|
||||
onclose?: () => void;
|
||||
onerror?: (error: Error) => void;
|
||||
onmessage?: (message: JSONRPCMessage) => void;
|
||||
|
||||
/**
|
||||
* Creates a new SSE server transport, which will direct the client to POST
|
||||
* messages to the relative or absolute URL identified by `endpoint`.
|
||||
*/
|
||||
constructor(endpoint: string, sessionId?: string | null) {
|
||||
this.#endpoint = endpoint;
|
||||
this.#sessionId = sessionId ?? crypto.randomUUID();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts processing messages on the transport.
|
||||
* This is called by the Server class and should not be called directly.
|
||||
*/
|
||||
async start(): Promise<void> {
|
||||
if (this.#stream) {
|
||||
throw new Error("FetchSSEServerTransport already started! If using Server class, note that connect() calls start() automatically.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the initial SSE connection request.
|
||||
* This should be called from your Remix loader to establish the SSE stream.
|
||||
*/
|
||||
async handleSSERequest(request: Request): Promise<Response> {
|
||||
const stream = new ReadableStream<string>({
|
||||
start: (controller) => {
|
||||
this.#stream = controller;
|
||||
|
||||
// Send headers
|
||||
controller.enqueue(": ping\n\n"); // Keep connection alive
|
||||
|
||||
// Send the endpoint event
|
||||
controller.enqueue(`event: endpoint\ndata: ${encodeURI(this.#endpoint)}?sessionId=${this.#sessionId}\n\n`);
|
||||
|
||||
// Handle cleanup when the connection closes
|
||||
request.signal.addEventListener("abort", () => {
|
||||
controller.close();
|
||||
this.#stream = undefined;
|
||||
this.onclose?.();
|
||||
});
|
||||
},
|
||||
cancel: () => {
|
||||
this.#stream = undefined;
|
||||
this.onclose?.();
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
Connection: "keep-alive",
|
||||
"Mcp-Session-Id": this.#sessionId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles incoming POST messages.
|
||||
* This should be called from your Remix action to handle incoming messages.
|
||||
*/
|
||||
async handlePostMessage(request: Request): Promise<Response> {
|
||||
if (!this.#stream) {
|
||||
const message = i18nT("mcp.errors.sseConnectionNotEstablished");
|
||||
return new Response(message, { status: 500 });
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
const contentType = request.headers.get("content-type");
|
||||
if (contentType !== "application/json") {
|
||||
throw new Error(`Unsupported content-type: ${contentType}`);
|
||||
}
|
||||
|
||||
body = await request.json();
|
||||
} catch (error) {
|
||||
this.onerror?.(error as Error);
|
||||
return new Response(String(error), { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
await this.handleMessage(body);
|
||||
} catch (error) {
|
||||
mcpTransportLogger.error({ err: error }, "Failed to handle MCP message");
|
||||
return new Response(`Invalid message: ${body}`, { status: 400 });
|
||||
}
|
||||
|
||||
return new Response("Accepted", { status: 202 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a client message, regardless of how it arrived.
|
||||
*/
|
||||
async handleMessage(message: unknown): Promise<void> {
|
||||
let parsedMessage: JSONRPCMessage;
|
||||
try {
|
||||
parsedMessage = JSONRPCMessageSchema.parse(message);
|
||||
} catch (error) {
|
||||
this.onerror?.(error as Error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
this.onmessage?.(parsedMessage);
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
this.#stream?.close();
|
||||
this.#stream = undefined;
|
||||
this.onclose?.();
|
||||
}
|
||||
|
||||
async send(message: JSONRPCMessage): Promise<void> {
|
||||
if (!this.#stream) {
|
||||
throw new Error("Not connected");
|
||||
}
|
||||
|
||||
// Send the message through the event stream
|
||||
this.#stream.enqueue(`event: message\ndata: ${JSON.stringify(message)}\n\n`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the session ID for this transport.
|
||||
* This can be used to route incoming POST requests.
|
||||
*/
|
||||
get sessionId(): string {
|
||||
return this.#sessionId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
__clearMcpRegistryForTests,
|
||||
createMcpExternalToolsProvider,
|
||||
listMcpToolsForChatbot,
|
||||
registerMcpToolForChatbot,
|
||||
unregisterMcpToolForChatbot,
|
||||
} from "./mcp-registry.server";
|
||||
|
||||
describe("mcp-registry", () => {
|
||||
beforeEach(() => {
|
||||
__clearMcpRegistryForTests();
|
||||
});
|
||||
|
||||
it("registers, lists, and unregisters tools", () => {
|
||||
registerMcpToolForChatbot({ toolName: "ping", description: "ping" });
|
||||
registerMcpToolForChatbot({ toolName: "stat", description: "stat" });
|
||||
expect(listMcpToolsForChatbot().map((t) => t.toolName)).toEqual(["ping", "stat"]);
|
||||
unregisterMcpToolForChatbot("ping");
|
||||
expect(listMcpToolsForChatbot().map((t) => t.toolName)).toEqual(["stat"]);
|
||||
});
|
||||
|
||||
it("ExternalToolsProvider.list returns the registered tools (tenant-aware boundary)", async () => {
|
||||
registerMcpToolForChatbot({ toolName: "ping", description: "ping" });
|
||||
const provider = createMcpExternalToolsProvider();
|
||||
const tools = await provider.list("tenant-a");
|
||||
expect(tools).toEqual([{ toolName: "ping", description: "ping" }]);
|
||||
});
|
||||
|
||||
it("ExternalToolsProvider.invoke forwards tenant + user to the tool invoker", async () => {
|
||||
const invoke = vi.fn(async (inputs, ctx) => ({ ok: true, ctx, inputs }));
|
||||
registerMcpToolForChatbot({ toolName: "ping", description: "ping", invoke });
|
||||
const provider = createMcpExternalToolsProvider();
|
||||
const out = await provider.invoke({ tenantId: "tenant-a", userId: "u1", toolName: "ping", inputs: { hi: 1 } });
|
||||
expect(invoke).toHaveBeenCalledOnce();
|
||||
expect(invoke).toHaveBeenCalledWith({ hi: 1 }, { tenantId: "tenant-a", userId: "u1" });
|
||||
expect(out).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it("invoke throws when the tool is not registered (no LLM-driven impersonation)", async () => {
|
||||
const provider = createMcpExternalToolsProvider();
|
||||
await expect(
|
||||
provider.invoke({ tenantId: "tenant-a", userId: "u1", toolName: "unknown", inputs: {} }),
|
||||
).rejects.toThrow(/not registered/);
|
||||
});
|
||||
|
||||
it("invoke returns a structured not-invocable payload for read-only tools", async () => {
|
||||
registerMcpToolForChatbot({ toolName: "ping", description: "ping" });
|
||||
const provider = createMcpExternalToolsProvider();
|
||||
const out = await provider.invoke({ tenantId: "tenant-a", userId: "u1", toolName: "ping", inputs: {} });
|
||||
expect(out).toMatchObject({ status: "not-invocable", toolName: "ping" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* MCP-registry adapter for the chatbot V2 `external_tools` capability.
|
||||
*
|
||||
* The MCP server (`mcp.server.ts`) registers tools at boot via
|
||||
* `registerMcpTools` and via `addToolRegistrar`. There is no public
|
||||
* `listTools` accessor on the underlying SDK server, so we mirror the
|
||||
* registrations into a process-local registry the chatbot reads.
|
||||
*
|
||||
* Tenant scope: MCP tools are presently registered globally — every
|
||||
* tenant sees the same set. The registry helper still takes a
|
||||
* `tenantId` so callers can hard-filter once per-tenant registries
|
||||
* arrive (Phase 06 plugin system). For now the tenant arg is recorded
|
||||
* in the audit-log via the high-risk wrapper that consumes this
|
||||
* registry.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Local contract for an external-tools provider. Previously imported from the
|
||||
* (now-removed) chatbot module; kept here as a self-contained interface so the
|
||||
* MCP registry stays usable by future MCP-server callers without depending on
|
||||
* the deleted self-hosted-AI surface.
|
||||
*/
|
||||
export interface ExternalToolsProvider {
|
||||
list: (tenantId: string) => Promise<ReadonlyArray<{ toolName: string; description: string }>>;
|
||||
invoke: (input: { tenantId: string; userId: string | null; toolName: string; inputs: Record<string, unknown> }) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export interface RegisteredMcpTool {
|
||||
readonly toolName: string;
|
||||
readonly description: string;
|
||||
/** Optional invoker; when set, the chatbot can call this tool. */
|
||||
readonly invoke?: (input: Record<string, unknown>, ctx: { tenantId: string; userId: string | null }) => Promise<unknown>;
|
||||
}
|
||||
|
||||
const registry = new Map<string, RegisteredMcpTool>();
|
||||
const READ_ONLY_TOOL_MESSAGE = "Tool is registered but cannot be invoked via the chatbot in this build.";
|
||||
|
||||
/**
|
||||
* Register an MCP tool so the chatbot's `external_tools` capability can
|
||||
* list and invoke it. Subsequent registrations of the same `toolName`
|
||||
* overwrite — last writer wins.
|
||||
*/
|
||||
export function registerMcpToolForChatbot(tool: RegisteredMcpTool): void {
|
||||
registry.set(tool.toolName, tool);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop a tool from the registry. Intended for tests + hot-reload
|
||||
* scenarios.
|
||||
*/
|
||||
export function unregisterMcpToolForChatbot(toolName: string): void {
|
||||
registry.delete(toolName);
|
||||
}
|
||||
|
||||
export function listMcpToolsForChatbot(): ReadonlyArray<RegisteredMcpTool> {
|
||||
return Array.from(registry.values()).sort((a, b) => a.toolName.localeCompare(b.toolName));
|
||||
}
|
||||
|
||||
export function __clearMcpRegistryForTests(): void {
|
||||
registry.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adapter implementing `ExternalToolsProvider` for the chatbot
|
||||
* capability. Tenant-aware list filter + audit-friendly invocation
|
||||
* (the wrapped tool factory adds AuditEvent rows).
|
||||
*/
|
||||
export function createMcpExternalToolsProvider(): ExternalToolsProvider {
|
||||
return {
|
||||
list: async (_tenantId: string) => {
|
||||
const tools = listMcpToolsForChatbot();
|
||||
return tools.map((t) => ({ toolName: t.toolName, description: t.description }));
|
||||
},
|
||||
invoke: async ({ tenantId, userId, toolName, inputs }) => {
|
||||
const tool = registry.get(toolName);
|
||||
if (!tool) {
|
||||
throw new Error(`MCP tool not registered: ${toolName}`);
|
||||
}
|
||||
if (!tool.invoke) {
|
||||
// Tool is listed (read-only) but has no chatbot-side invoker —
|
||||
// surface a structured payload so the LLM relays the limitation
|
||||
// to the user rather than fabricating a result.
|
||||
return {
|
||||
status: "not-invocable",
|
||||
toolName,
|
||||
message: READ_ONLY_TOOL_MESSAGE,
|
||||
};
|
||||
}
|
||||
return tool.invoke(inputs, { tenantId, userId });
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { z } from "zod/v3";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
const mcpToolsLogger = createScopedLogger("mcp.tools");
|
||||
|
||||
export function registerMcpTools(server: McpServer) {
|
||||
// Public tools - no authentication required
|
||||
|
||||
server.registerTool(
|
||||
"healthcheck",
|
||||
{
|
||||
description: i18nT("mcp.tools.healthcheck.description"),
|
||||
inputSchema: z.object({}),
|
||||
},
|
||||
async () => {
|
||||
mcpToolsLogger.info("[MCP] healthcheck");
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify({
|
||||
status: "ok",
|
||||
version: "1.0.0",
|
||||
timestamp: new Date().toISOString(),
|
||||
}),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { FetchSSEServerTransport } from "./fetch-transport.server";
|
||||
import { registerMcpTools } from "./mcp-tools.server";
|
||||
|
||||
type McpToolRegistrar = (server: McpServer) => void;
|
||||
|
||||
export const server = new McpServer(
|
||||
{
|
||||
name: "app-mcp",
|
||||
version: "1.0.0",
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
tools: {},
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// Register MCP tools
|
||||
registerMcpTools(server);
|
||||
|
||||
// Tool registrar storage for app-specific tools
|
||||
const toolRegistrars: McpToolRegistrar[] = [];
|
||||
|
||||
/**
|
||||
* Register a tool registrar that will add custom MCP tools.
|
||||
* This allows apps to extend the MCP server with their own tools.
|
||||
*/
|
||||
export function addToolRegistrar(registrar: McpToolRegistrar) {
|
||||
toolRegistrars.push(registrar);
|
||||
registrar(server);
|
||||
}
|
||||
|
||||
const transports = new Map<string, FetchSSEServerTransport>();
|
||||
const MAX_TRANSPORTS = 64;
|
||||
|
||||
export async function connect(sessionId?: string | null) {
|
||||
const transport = new FetchSSEServerTransport("/mcp", sessionId);
|
||||
transport.onclose = () => {
|
||||
transports.delete(transport.sessionId);
|
||||
};
|
||||
await server.connect(transport);
|
||||
pruneTransports();
|
||||
transports.set(transport.sessionId, transport);
|
||||
return transport;
|
||||
}
|
||||
|
||||
export async function getTransport(sessionId: string) {
|
||||
return transports.get(sessionId);
|
||||
}
|
||||
|
||||
function pruneTransports() {
|
||||
while (transports.size >= MAX_TRANSPORTS) {
|
||||
const oldestSessionId = transports.keys().next().value;
|
||||
if (!oldestSessionId) {
|
||||
return;
|
||||
}
|
||||
transports.delete(oldestSessionId);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user