ProjectOS / packages /mcp-fabric /src /adapters.ts
AnthropicallyHuggingFaces's picture
Sync full ProjectOS monorepo from GitHub 7f633f5
a8f4b72 verified
Raw History Blame Contribute Delete
9.88 kB
import { mkdir } from 'node:fs/promises';
import { existsSync, statSync } from 'node:fs';
import { delimiter, dirname, join, resolve } from 'node:path';
import { spawn, type ChildProcess } from 'node:child_process';
import { fileURLToPath } from 'node:url';
export type AdapterName = 'filesystem' | 'git' | 'github' | 'postgres' | 'fetch' | 'memory';
export type ServerDefinition = {
name: string;
adapter: string;
trust: string;
enabled: boolean;
authMode: 'none' | 'oauth' | 'environment' | 'keyring';
credentialRef?: string;
accessMode: 'read-only' | 'read-write';
};
export type AdapterDescriptor = {
name: AdapterName;
title: string;
description: string;
source: string;
transport: 'stdio';
requires: string[];
};
export const adapterCatalog: Record<AdapterName, AdapterDescriptor> = {
filesystem: {
name: 'filesystem', title: 'Model Context Protocol filesystem server',
description: 'Local file tools limited to the ProjectOS workspace root.',
source: 'https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem', transport: 'stdio', requires: ['Node.js 24.22.1+ or 26.12.1+', 'npm CLI']
},
git: {
name: 'git', title: 'Model Context Protocol Git server',
description: 'Repository-scoped Git inspection and operations; requires PROJECTOS_GIT_ROOT.',
source: 'https://github.com/modelcontextprotocol/servers/tree/main/src/git', transport: 'stdio', requires: ['uvx', 'PROJECTOS_GIT_ROOT']
},
github: {
name: 'github', title: 'GitHub official MCP server',
description: 'GitHub API tools; browser OAuth is the default and read profiles enable server read-only mode.',
source: 'https://github.com/github/github-mcp-server', transport: 'stdio', requires: ['Docker', 'browser sign-in on first use']
},
postgres: {
name: 'postgres', title: 'Microsoft PostgreSQL MCP server',
description: 'PostgreSQL tools using a saved OS keyring connection profile.',
source: 'https://github.com/microsoft/postgres-mcp', transport: 'stdio', requires: ['Node.js', 'npm CLI', 'OS keyring connection profile']
},
fetch: {
name: 'fetch', title: 'Model Context Protocol fetch server',
description: 'Fetches public web pages and extracts readable content.',
source: 'https://github.com/modelcontextprotocol/servers/tree/main/src/fetch', transport: 'stdio', requires: ['uvx']
},
memory: {
name: 'memory', title: 'Model Context Protocol memory server',
description: 'Local persistent knowledge graph stored in ProjectOS data/.',
source: 'https://github.com/modelcontextprotocol/servers/tree/main/src/memory', transport: 'stdio', requires: ['Node.js 24.22.1+ or 26.12.1+', 'npm CLI']
}
};
export type LaunchSpec = { command: string; args: string[]; cwd: string; env: NodeJS.ProcessEnv };
const sourceDirectory = dirname(fileURLToPath(import.meta.url));
export const projectRoot = resolve(sourceDirectory, '../../..');
const npxCli = findNpxCli();
function findNpxCli(): string | undefined {
const candidates = [
process.env.PROJECTOS_NPX_CLI,
resolve(dirname(process.execPath), '../lib/node_modules/npm/bin/npx-cli.js'),
resolve(dirname(process.execPath), '../node_modules/npm/bin/npx-cli.js'),
'C:/Program Files/nodejs/node_modules/npm/bin/npx-cli.js',
...String(process.env.PATH ?? '').split(delimiter).flatMap((part) => [
join(part, 'node_modules/npm/bin/npx-cli.js'),
join(dirname(part), 'node_modules/npm/bin/npx-cli.js')
])
].filter((value): value is string => Boolean(value));
return candidates.find((candidate) => {
try { return statSync(candidate).isFile(); } catch { return false; }
});
}
function inheritedEnvironment(): NodeJS.ProcessEnv {
const allowed = ['PATH', 'PATHEXT', 'SYSTEMROOT', 'WINDIR', 'TEMP', 'TMP', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'HOME', 'HOMEDRIVE', 'HOMEPATH', 'LANG'];
return Object.fromEntries(allowed.flatMap((key) => process.env[key] === undefined ? [] : [[key, process.env[key]!]]));
}
function findExecutable(name: string): string | undefined {
const suffixes = process.platform === 'win32' ? (process.env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';') : [''];
for (const entry of String(process.env.PATH ?? '').split(delimiter)) {
for (const suffix of ['', ...suffixes]) {
const candidate = join(entry, `${name}${suffix}`);
try { if (statSync(candidate).isFile()) return candidate; } catch { /* keep searching PATH */ }
}
}
return undefined;
}
export function missingPrerequisites(adapter: string, credentialRef?: string): string[] {
const missing: string[] = [];
if (!adapterCatalog[adapter as AdapterName]) return [`No adapter registered for '${adapter}'.`];
if (credentialRef && !process.env[credentialRef]?.trim()) missing.push(`credential ${credentialRef} is not configured`);
if (adapter === 'filesystem' || adapter === 'memory') {
const [major = 0, minor = 0, patch = 0] = process.versions.node.split('.').map(Number);
const supportedRuntime = (major === 24 && (minor > 22 || (minor === 22 && patch >= 1))) || (major === 26 && (minor > 12 || (minor === 12 && patch >= 1))) || major > 26;
if (!supportedRuntime) missing.push('Node.js 24.22.1+ or 26.12.1+ is required by the upstream server security release');
}
if (adapter === 'filesystem' || adapter === 'memory' || adapter === 'postgres') {
if (!npxCli) missing.push('npm CLI was not found; set PROJECTOS_NPX_CLI to npx-cli.js');
}
if (adapter === 'github' && !findExecutable('docker')) missing.push('Docker is not available on PATH');
if ((adapter === 'git' || adapter === 'fetch') && !findExecutable('uvx')) missing.push('uvx is not available on PATH');
if (adapter === 'git' && !process.env.PROJECTOS_GIT_ROOT?.trim()) missing.push('PROJECTOS_GIT_ROOT is not configured');
if (adapter === 'git' && process.env.PROJECTOS_GIT_ROOT && !exists(process.env.PROJECTOS_GIT_ROOT)) missing.push('PROJECTOS_GIT_ROOT does not exist');
return missing;
}
function exists(path: string): boolean {
return existsSync(path);
}
export async function createLaunchSpec(server: ServerDefinition): Promise<LaunchSpec> {
const env = inheritedEnvironment();
const npx = (args: string[]): LaunchSpec => {
if (!npxCli) throw new Error('npm CLI was not found; set PROJECTOS_NPX_CLI to npx-cli.js.');
return { command: process.execPath, args: [npxCli, ...args], cwd: projectRoot, env };
};
switch (server.adapter as AdapterName) {
case 'filesystem':
return npx(['-y', '@modelcontextprotocol/server-filesystem@2.1.0', resolve(process.env.PROJECTOS_MCP_FILESYSTEM_ROOT || projectRoot)]);
case 'memory': {
const memoryPath = resolve(projectRoot, 'data/mcp-memory.jsonl');
await mkdir(dirname(memoryPath), { recursive: true });
return { ...npx(['-y', '@modelcontextprotocol/server-memory@2.0.1']), env: { ...env, MEMORY_FILE_PATH: memoryPath } };
}
case 'postgres': {
const profileName = server.credentialRef ? process.env[server.credentialRef]?.trim() : undefined;
return { ...npx(['-y', '@microsoft/postgres-mcp', 'run']), env: { ...env, POSTGRES_MCP_DISABLE_CWD_ACCESS: '1', ...(profileName ? { POSTGRES_MCP_PROFILE_NAME: profileName } : {}) } };
}
case 'github': {
const args = ['run', '--rm', '-i', '--pull=missing', '-e', 'GITHUB_LOCKDOWN_MODE'];
const childEnv: NodeJS.ProcessEnv = { ...env, GITHUB_LOCKDOWN_MODE: '1' };
if (server.authMode === 'oauth') {
const callbackPort = Number(process.env.PROJECTOS_GITHUB_OAUTH_CALLBACK_PORT || '8085');
if (!Number.isInteger(callbackPort) || callbackPort < 1024 || callbackPort > 65535) throw new Error('PROJECTOS_GITHUB_OAUTH_CALLBACK_PORT must be a port from 1024 through 65535.');
args.push('-p', `127.0.0.1:${callbackPort}:${callbackPort}`, '-e', 'GITHUB_OAUTH_CALLBACK_PORT');
childEnv.GITHUB_OAUTH_CALLBACK_PORT = String(callbackPort);
} else if (server.authMode === 'environment' && server.credentialRef) {
const token = process.env[server.credentialRef];
if (!token) throw new Error(`Credential reference ${server.credentialRef} is not configured.`);
args.push('-e', 'GITHUB_PERSONAL_ACCESS_TOKEN');
childEnv.GITHUB_PERSONAL_ACCESS_TOKEN = token;
} else {
throw new Error(`GitHub authentication mode '${server.authMode}' is not supported by this adapter.`);
}
if (server.accessMode === 'read-only') {
args.push('-e', 'GITHUB_READ_ONLY');
childEnv.GITHUB_READ_ONLY = '1';
}
args.push('ghcr.io/github/github-mcp-server:v2.0.3');
return { command: findExecutable('docker') ?? 'docker', args, cwd: projectRoot, env: childEnv };
}
case 'fetch': {
const uvx = findExecutable('uvx');
if (!uvx) throw new Error('uvx is not available on PATH. Install uv or configure the fetch adapter.');
return { command: uvx, args: ['--from', 'mcp-server-fetch==2026.10.28', 'mcp-server-fetch'], cwd: projectRoot, env: { ...env, PYTHONIOENCODING: 'utf-8' } };
}
case 'git': {
const root = process.env.PROJECTOS_GIT_ROOT?.trim();
const uvx = findExecutable('uvx');
if (!root) throw new Error('PROJECTOS_GIT_ROOT is required for the Git adapter.');
if (!uvx) throw new Error('uvx is not available on PATH. Install uv or configure the Git adapter.');
return { command: uvx, args: ['--from', 'mcp-server-git==2026.10.28', 'mcp-server-git', '--repository', resolve(root)], cwd: projectRoot, env };
}
default:
throw new Error(`No launch configuration is registered for adapter '${server.adapter}'.`);
}
}
export function spawnAdapter(spec: LaunchSpec): ChildProcess {
return spawn(spec.command, spec.args, {
cwd: spec.cwd,
env: spec.env,
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
shell: false
});
}