Files
LangBot/skills/src/commands/env.ts
T
Junyan Chin e9dd584792 feat: MCP server + in-repo skills (agent-friendly platform) (#2269)
* feat(api): support global API key from config.yaml (api.global_api_key)

Accept a config-defined global API key anywhere a web-UI key is accepted
(X-API-Key / Bearer), with no login session and no DB record. Useful for
automated deployments and AI agents (HTTP API + MCP). Defaults to empty
(disabled); does not require the lbk_ prefix.

- templates/config.yaml: add api.global_api_key with security notes
- service/apikey.py: verify_api_key checks global key first (constant-time)
- docs/API_KEY_AUTH.md: document the global key + security guidance
- tests: cover global-key match, prefix-free, fallback-to-db, disabled

* feat(mcp): expose LangBot management as an MCP server at /mcp

Add an MCP (Model Context Protocol) server so external AI agents can manage a
LangBot instance. Reuses the same API-key auth as the HTTP API (including the
config.yaml global API key).

- pkg/api/mcp/server.py: FastMCP server wrapping the service layer; 21 curated
  tools across system/bots/pipelines/models/knowledge/mcp-servers/skills
- pkg/api/mcp/mount.py: ASGI dispatcher fronting Quart; authenticates /mcp
  requests with an API key, runs the streamable-HTTP session manager lifespan
- controller/main.py: serve the wrapped ASGI app via hypercorn (was run_task)
- web: new 'MCP' tab in the API integration dialog showing endpoint, auth, and
  client config; i18n for 8 locales
- tests/manual/mcp_smoke.py: e2e check (401 unauth, list tools, call tools)

Tool surface is intentionally curated (not all ~25 route groups) to keep the
agent surface small, safe, and maintainable. Extend deliberately.

* feat(skills): add in-repo skills/ as the single source of truth

Migrate the agent skills + QA/e2e test harness from the (now archived)
langbot-app/langbot-skills repo into LangBot/skills/, and add four new skills.

Migrated:
- langbot-plugin-dev, langbot-testing (e2e), langbot-env-setup,
  langbot-skills-maintenance, langbot-eba-adapter-dev
- the bin/lbs CLI (src/, test/, scripts/, schemas/, qa-agent-docs/)

New:
- langbot-dev      core backend + web development
- langbot-deploy   Docker/K8s deployment + config.yaml + global API key
- langbot-mcp-ops  operating the LangBot MCP server (/mcp)
- langbot-space-ops operating the Space marketplace MCP server

- src/cli.ts repoRoot(): recognize the skills assets root (skills.index.json +
  bin/lbs) so the CLI works when nested inside the LangBot repo
- README.md: unified skill catalog; skills.index.json regenerated

Parity with source verified: bin/lbs validate + node test suite match the
source repo (only the uncommitted .lbpkg build-artifact fixture differs).

* docs(agents): document agent-facing surfaces + API/MCP/skills sync rule

* docs(readme): add 'Built for AI Agents' section across all locales

Highlight MCP server, in-repo skills (single source of truth), AGENTS.md
sync rule, and llms.txt. Cross-link LangBot Space MCP marketplace.

* style(mcp): fix ruff format + prettier lint in MCP server and API panel

* style(web): prettier format MCP i18n locale entries

* docs(skills): note MCP instance control in dev/testing skills

All development-guidance skills now point to the LangBot instance MCP
server (/mcp) and the Space marketplace MCP server, reusing API keys.
2026-06-20 15:14:47 +08:00

141 lines
5.2 KiB
TypeScript

import { existsSync } from "node:fs";
import { Socket } from "node:net";
import type { CommandContext } from "../types.ts";
import { parseOptions } from "../cli.ts";
import { loadEnv } from "../fs.ts";
import { requiredEnvKeys } from "../constants.ts";
import { redactEnvValue } from "../readiness.ts";
export function commandEnvShow(ctx: CommandContext): number {
const { options } = parseOptions(ctx.args.slice(2));
const env = loadEnv(ctx.root);
const outputEnv = Object.fromEntries(
Object.entries(env).map(([key, value]) => [key, redactEnvValue(key, value)]),
);
if (options.json === true) {
console.log(JSON.stringify(outputEnv, null, 2));
return 0;
}
for (const key of Object.keys(outputEnv).sort()) {
console.log(`${key}=${outputEnv[key]}`);
}
return 0;
}
async function checkUrl(label: string, url: string): Promise<{ ok: boolean; message: string }> {
if (!url) return { ok: false, message: `${label}: missing` };
const displayUrl = redactEnvValue(label, url);
try {
const response = await fetch(url, { method: "HEAD", signal: AbortSignal.timeout(2500) });
return { ok: response.ok || response.status < 500, message: `${label}: ${displayUrl} -> HTTP ${response.status}` };
} catch (error) {
return { ok: false, message: `${label}: ${displayUrl} -> ${String(error).replace(/\s+/g, " ")}` };
}
}
function endpoint(url: string): { host: string; port: number } | null {
try {
const parsed = new URL(url);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
const port = parsed.port ? Number(parsed.port) : parsed.protocol === "https:" ? 443 : 80;
return { host: parsed.hostname, port };
} catch {
return null;
}
}
async function checkTcpListener(url: string): Promise<{ ok: boolean; message: string } | null> {
const target = endpoint(url);
if (!target) return null;
return await new Promise((resolve) => {
const socket = new Socket();
let settled = false;
const finish = (ok: boolean, detail: string) => {
if (settled) return;
settled = true;
socket.destroy();
resolve({
ok,
message: `${target.host}:${target.port} ${detail}`,
});
};
socket.setTimeout(1500);
socket.once("connect", () => finish(true, "is listening"));
socket.once("timeout", () => finish(false, "did not accept TCP connection before timeout"));
socket.once("error", (error) => finish(false, `is not listening (${error.message})`));
socket.connect(target.port, target.host);
});
}
function startupHint(label: string, env: Record<string, string>): string | null {
if (label === "LANGBOT_BACKEND_URL" && env.LANGBOT_REPO) {
return `start backend: cd ${env.LANGBOT_REPO} && uv run main.py`;
}
if (label === "LANGBOT_FRONTEND_URL" && env.LANGBOT_WEB_REPO) {
return `start frontend: cd ${env.LANGBOT_WEB_REPO} && pnpm dev`;
}
return null;
}
function compareProxyPair(env: Record<string, string>, upper: string, lower: string): string | null {
const upperValue = process.env[upper] ?? env[upper] ?? "";
const lowerValue = process.env[lower] ?? env[lower] ?? "";
if (upperValue && lowerValue && upperValue !== lowerValue) {
return `${upper}/${lower}: mismatch (${redactEnvValue(upper, upperValue)} vs ${redactEnvValue(lower, lowerValue)})`;
}
return null;
}
export async function commandEnvDoctor(ctx: CommandContext): Promise<number> {
const env = loadEnv(ctx.root);
const failures: string[] = [];
const warnings: string[] = [];
for (const key of requiredEnvKeys) {
if (!env[key]) failures.push(`missing ${key}`);
}
for (const [label, path] of [
["LANGBOT_REPO", env.LANGBOT_REPO],
["LANGBOT_WEB_REPO", env.LANGBOT_WEB_REPO],
["LANGBOT_CHROMIUM_EXECUTABLE", env.LANGBOT_CHROMIUM_EXECUTABLE],
]) {
if (!path || !existsSync(path)) failures.push(`${label}: path does not exist (${path || "missing"})`);
}
if (env.LANGBOT_BROWSER_PROFILE && !existsSync(env.LANGBOT_BROWSER_PROFILE)) {
warnings.push(`LANGBOT_BROWSER_PROFILE: path does not exist yet (${env.LANGBOT_BROWSER_PROFILE})`);
}
for (const mismatch of [
compareProxyPair(env, "HTTP_PROXY", "http_proxy"),
compareProxyPair(env, "HTTPS_PROXY", "https_proxy"),
compareProxyPair(env, "ALL_PROXY", "all_proxy"),
compareProxyPair(env, "NO_PROXY", "no_proxy"),
]) {
if (mismatch) failures.push(mismatch);
}
for (const [label, result] of await Promise.all([
checkUrl("LANGBOT_BACKEND_URL", env.LANGBOT_BACKEND_URL).then((result) => ["LANGBOT_BACKEND_URL", result] as const),
checkUrl("LANGBOT_FRONTEND_URL", env.LANGBOT_FRONTEND_URL).then((result) => ["LANGBOT_FRONTEND_URL", result] as const),
])) {
if (result.ok) console.log(`OK: ${result.message}`);
else {
failures.push(result.message);
const tcp = await checkTcpListener(env[label]);
if (tcp && !tcp.ok) failures.push(`${label}: no HTTP service reachable because ${tcp.message}`);
const hint = startupHint(label, env);
if (hint) warnings.push(`${label}: ${hint}`);
}
}
for (const warning of warnings) console.log(`WARN: ${warning}`);
for (const failure of failures) console.log(`FAIL: ${failure}`);
if (failures.length > 0) return 1;
console.log("OK: environment looks usable");
return 0;
}