ksp-mcp
状态:早期开发
序章
早在第一个勇敢的Kerbal敢于问“这个按钮是干什么的?”之前,回到Kerbin的工程师们就达到了一个艰难的极限:思考很重。
深空飞船根本无法携带运行先进LLM所需的质量、功率消耗或冷却系统。解决方案不是更多的电池或更大的散热器,而是在KWS、Koogle和Kzure上进行云托管!
ksp-mcp将允许航天器被Kerbin上托管的LLM使用。
超越第四面墙的目的
MCP(模型上下文协议)服务器,用于通过kOS和MechJeb2实现Kerbal太空计划自动化。
使LLM能够通过kOS脚本和MechJeb自动驾驶仪功能直接控制KSP航天器。
先决条件
- 克尔巴尔太空计划 具有以下mods:
- kOS -脚本编写和自动化 - MechJeb2(开发) -自动驾驶仪和机动计划 - kOS。MechJeb2.插件(开发) -将MechJeb暴露给kOS(需要开发版本-在开发完成之前,需要对belpyro的工作进行分叉)
- kOS Telnet服务器 已启用(在KSP设置中配置)
安装
npm install ksp-mcp或来源:
git clone https://github.com/caseys/ksp-mcp
cd ksp-mcp
npm install
npm run build用法
作为Types/JavaScript库
直接在TypeScript或JavaScript项目中导入ksp-mcp:
import { KosConnection, config } from 'ksp-mcp';
// Connect to kOS
const conn = new KosConnection();
await conn.connect();
// Execute kOS commands
const result = await conn.execute('PRINT "Hello from kOS".');
console.log(result.output);
// Disconnect
await conn.disconnect();可用出口
// Core connection
import { KosConnection } from 'ksp-mcp';
import type { ConnectionState, CommandResult, KosConnectionOptions } from 'ksp-mcp';
// Transport layer
import { BaseTransport, SocketTransport, TmuxTransport } from 'ksp-mcp';
import type { Transport } from 'ksp-mcp';
// MechJeb interface - High-level (recommended)
import { ManeuverOrchestrator, withTargetAndExecute } from 'ksp-mcp';
import type { ManeuverOptions, OrchestratedResult } from 'ksp-mcp';
// MechJeb interface - Low-level
import { MechJebClient, ManeuverProgram, AscentProgram, AscentHandle } from 'ksp-mcp';
// MechJeb operations (direct functions)
import {
executeNode, getNodeProgress,
ellipticize, changeSemiMajorAxis,
changeEccentricity, changeLAN, changeLongitudeOfPeriapsis,
matchPlane, killRelativeVelocity,
resonantOrbit, returnFromMoon, interplanetaryTransfer
} from 'ksp-mcp';
// MechJeb telemetry
import { getVesselState, getOrbitInfo, getMechJebInfo, getShipTelemetry } from 'ksp-mcp';
import type { ShipTelemetry, VesselInfo, OrbitTelemetry, ManeuverInfo, EncounterInfo, TargetInfo } from 'ksp-mcp';
// MechJeb discovery
import { discoverModules, isMechJebAvailable } from 'ksp-mcp';
// Configuration
import { config } from 'ksp-mcp';
import type { Config } from 'ksp-mcp';
// MCP Server
import { createServer } from 'ksp-mcp';
// Tool handlers (for direct use without MCP)
import { handleConnect, handleDisconnect, handleExecute, handleStatus, getConnection } from 'ksp-mcp';
import { handleListCpus } from 'ksp-mcp';
import type { CpuInfo } from 'ksp-mcp';
// Connection monitoring
import { KosMonitor, globalKosMonitor } from 'ksp-mcp';
import type { MonitorStatus, LoopDetection } from 'ksp-mcp';
// Save/Load (KUNIVERSE)
import { listQuicksaves, quicksave, quickload, canQuicksave } from 'ksp-mcp';
// Subpath imports also available
import { KosConnection } from 'ksp-mcp/transport';
import { MechJebClient, ManeuverOrchestrator } from 'ksp-mcp/mechjeb';
import { config } from 'ksp-mcp/config';
import { createServer } from 'ksp-mcp/server';
import * as daemon from 'ksp-mcp/daemon'; // Persistent connection daemon作为MCP服务器(标准-默认)
对于Claude Desktop和本地工具:
# Start with stdio transport (default)
ksp-mcp
# Or explicitly
ksp-mcp --transport stdio在Claude Code的MCP设置中配置:
{
"mcpServers": {
"ksp-mcp": {
"command": "npx",
"args": ["ksp-mcp"]
}
}
}或者使用本地安装:
{
"mcpServers": {
"ksp-mcp": {
"command": "node",
"args": ["/path/to/ksp-mcp/dist/index.js"]
}
}
}作为MCP服务器(HTTP网络)
使用网络访问 可流式HTTP传输:
# Start on localhost:3000 (stateful - session-based)
ksp-mcp --transport http --port 3000
# Listen on all interfaces
ksp-mcp --transport http --host 0.0.0.0 --port 3000
# Stateless mode (no session management)
ksp-mcp --transport http --stateless终点:
POST/GET/DELETE /mcp-MCP可流式HTTP端点GET /health-健康检查(显示会话计数)
客户端通过POSTing连接到 /mcp服务器在中返回会话ID mcp-session-id 必须包含在后续请求中的标头。
直接脚本使用
所有机动指挥支持 --no-execute 仅计划(创建节点而不执行)。
# Ascent
npm run launch-ascent # Launch to orbit with MechJeb
# Basic orbital maneuvers (auto-execute by default)
npm run circularize # Circularize at apoapsis
npm run circularize PERIAPSIS # Circularize at periapsis
npm run circularize -- --no-execute # Plan only
npm run adjust-periapsis # Adjust periapsis
npm run adjust-apoapsis # Adjust apoapsis
npm run ellipticize # Set both Pe and Ap
npm run change-semi-major-axis # Change semi-major axis
# Orbital adjustments
npm run change-inclination 0 # Change to 0° inclination
npm run change-inclination 0 EQ_NEAREST_AD # Specify timing
npm run change-inclination 0 -- --no-execute # Plan only
npm run change-eccentricity # Change eccentricity
npm run change-ascending-node # Change longitude of ascending node
npm run change-periapsis-longitude # Change longitude of periapsis
# Transfers
npm run hohmann-transfer # Transfer to Mun (default)
npm run hohmann-transfer Minmus # Transfer to Minmus
npm run hohmann-transfer Mun -- --capture # Include capture burn
npm run hohmann-transfer -- --no-execute # Plan only
npm run course-correct # Fine-tune approach
npm run interplanetary-transfer # Interplanetary transfer
npm run return-from-moon # Return from moon
npm run resonant-orbit # Resonant orbit for satellite deployment
# Rendezvous
npm run set-target # Set navigation target
npm run match-planes # Match orbital plane
npm run match-velocities # Match velocities at closest approach
# Node execution
npm run execute-node # Execute next maneuver node
# Time warp
npm run warp # Control time warp
# Save/Load
npm run load-save # Load a saved game
# Daemon (persistent connection)
npm run daemon:start # Start kOS connection daemon
npm run daemon:status # Check daemon status
npm run kos # Execute kOS command via daemonMCP工具
注: 与kOS的连接是自动的。所有工具在调用时都会自动连接。
连接和公用设施
- 状态 -获取舰船遥测数据(返回结构化JSON,包括舰船、轨道、机动、遭遇、目标和格式化输出)
- 断开 -断开与kOS的连接
- 命令 -执行原始kOS命令
- list_cpus -列出可用的kOS CPU
- switch_cpu -设置会话的CPU首选项(按ID或标签),或清除以自动选择
定向
- set_target -设定导航目标(身体或船只)
- get_target -获取当前目标信息
- clear_target -清除当前目标
时间控制
- 弯曲 -时间扭曲到事件(soi、node、periapsis、apoapsis)或秒
保存/加载
- load_save -加载已保存的游戏
- list_saves -列出可用保存
- 快速存档 -创建快速保存
基本机动
- adjust_periapsis -改变近缘高度
- adjust_apoapsis -更改远距高度
- 传阅 -圆形轨道
- 椭圆化 -设置近端和远端
- change_semi_major_axis -更改半长轴
轨道调整
- change_inclination -改变轨道倾角
- change_中心 -改变轨道偏心率
- change_ascening_node -更改上升节点的经度
- change_periapsis_longitude -改变近缘经度
会合
- match_planes -将轨道平面与目标匹配
- 匹配_速度 -将速度与目标匹配
转账
- 霍曼转移 -计划Hohmann转移到目标
- 课程_正确 -微调最接近的方法
- 共振轨道 -创建共振轨道
- return_from_moon -从月球返回母体
- 网间转移 -计划行星际转移
节点执行
- execute_node -执行下一个机动节点
- clear_nodes -删除所有机动节点
上升
- 洗衣店_香水 -发射到轨道
紧急情况
- 碰撞_失效 -紧急烧伤以提高根尖
MCP资源
MCP客户端的只读数据端点。通过以下方式访问 resources/read:
- ksp://status -船舶遥测(结构化JSON)
- ksp://targets -可用的尸体和船只
- ksp://target -当前导航目标
- ksp://saves -可用的流沙
状态资源架构
这 ksp://status 资源返回结构化数据:
{
"vessel": {
"name": "My Ship",
"type": "Ship",
"status": "ORBITING"
},
"orbit": {
"body": "Kerbin",
"apoapsis": 150000,
"periapsis": 100000,
"period": 2400,
"inclination": 0.5,
"eccentricity": 0.015,
"lan": 45.2
},
"maneuver": {
"deltaV": 500.5,
"timeToNode": 300,
"estimatedBurnTime": 45
},
"encounter": {
"body": "Mun",
"periapsis": 50000
},
"target": {
"name": "Mun",
"type": "Body",
"distance": 12000000
},
"formatted": "=== Ship Status ===\nVessel: My Ship (Ship) - ORBITING\n..."
}可选字段(maneuver, encounter, target)仅在适用时存在。
MCP提示
常见任务的工作流程模板:
- 发射到轨道 -标准上升工作流程
- Args: altitude (可选,默认“80km”)
- 转移到月球 -月球转移序列
- Args: target (必填:“Mun”或“Minmus”)
- 返回路缘 -从月球返回
- Args: targetPeriapsis (可选,默认“40km”)
任务流程示例
使用MCP工具
// Connection is automatic - just call the tools you need!
// 1. Launch to orbit
await launch({ altitude: 150000, inclination: 0 });
// 2. Set target and plan transfer
await set_target({ name: "Mun" });
await hohmann();
await execute_node();
// 3. Course correction
await course_correct({ targetDistance: 50000 });
await execute_node();
// 4. Warp to Mun, then circularize
await warp({ target: "soi" });
await circularize({ timeRef: "PERIAPSIS" });
await execute_node();使用库API
该库遵循“库优先”的架构,其中CLI和MCP是核心库的精简包装器。
import { KosConnection, ManeuverOrchestrator } from 'ksp-mcp';
const conn = new KosConnection();
await conn.connect();
const orchestrator = new ManeuverOrchestrator(conn);
// Transfer to Mun with auto-execution
const result = await orchestrator.hohmannTransfer('COMPUTED', false, {
target: 'Mun', // Auto-sets target
execute: true, // Auto-executes node (default)
});
if (result.success) {
console.log(`Transfer complete! ΔV: ${result.deltaV} m/s`);
}
// Or plan without executing
const planOnly = await orchestrator.circularize('APOAPSIS', { execute: false });
console.log(`Node created: ${planOnly.deltaV} m/s`);
await conn.disconnect();低级API
要获得更多控制,请使用 ManeuverProgram 直接:
import { KosConnection, ManeuverProgram, executeNode } from 'ksp-mcp';
const conn = new KosConnection();
await conn.connect();
const maneuver = new ManeuverProgram(conn);
// Set target manually
await maneuver.setTarget('Mun', 'body');
// Plan transfer (does not execute)
const result = await maneuver.hohmannTransfer('COMPUTED', false);
// Execute separately
if (result.success) {
await executeNode(conn);
}
await conn.disconnect();配置
创建 .env 文件(或复制自 .env.example):
# kOS Telnet Server
KOS_HOST=127.0.0.1
KOS_PORT=5410
# Default CPU selection
KOS_CPU_ID=0
# or use label:
# KOS_CPU_LABEL=guidance项目结构
src/
├── cli/ # CLI command entry points
│ ├── mechjeb/ # MechJeb maneuver commands
│ │ ├── ascent/ # Launch commands
│ │ ├── basic/ # Basic maneuvers (circularize, etc.)
│ │ ├── orbital/ # Orbital adjustments
│ │ ├── rendezvous/ # Rendezvous operations
│ │ └── transfer/ # Transfer maneuvers
│ ├── kos/ # kOS utility commands
│ └── daemon-cli.ts # Daemon control
├── lib/ # Core library (public API)
│ ├── index.ts # Public exports
│ ├── types.ts # Type definitions
│ ├── mechjeb/ # MechJeb operations
│ │ ├── orchestrator.ts # High-level API with target/execute
│ │ ├── ascent.ts # Ascent guidance
│ │ ├── telemetry.ts # Vessel/orbit info
│ │ ├── basic/ # Basic maneuvers
│ │ ├── orbital/ # Orbital adjustments
│ │ ├── rendezvous/ # Rendezvous operations
│ │ └── transfer/ # Transfer maneuvers
│ └── kos/ # kOS utilities (warp, nodes, etc.)
├── service/ # Server implementations
│ ├── http-server.ts # MCP server (stdio + HTTP)
│ └── cli-daemon.ts # Background connection daemon
├── transport/ # kOS connection layer
│ ├── kos-connection.ts # Main connection class
│ ├── socket-transport.ts # TCP socket transport
│ └── tmux-transport.ts # Tmux transport (fallback)
├── config/ # Configuration
└── utils/ # Utility functionsCLI选项
ksp-mcp [options]
Options:
-t, --transport Transport type: stdio (default), http
-p, --port
Port for HTTP transport (default: 3000)
-h, --host Host for HTTP transport (default: 127.0.0.1)
--stateless Run HTTP in stateless mode (no sessions)
--help Show help实施说明
kOS协议与完成检测
ksp-mcp使用多种模式在kOS中进行可靠的命令完成检测:
基于哨兵的完成
对于大多数命令, KosConnection.execute() 在每次命令后自动注射哨兵标记。流程为:
- 发送用户命令
- 发送
PRINT "__MCP_DONE___".带有唯一令牌 - 等待输出中的哨兵-这确认kOS执行了两个命令
- 从输出中去除回声、提示和哨兵
看 docs/kos-protocol-analysis.md 了解完整的协议细节。
多行kOS脚本
在TypeScript中嵌入多行kOS脚本时,通常会使用 .replaceAll('\n', ' '). 从不使用 // 这些脚本中的注释 -他们将在现在的单行线上评论他们之后的一切。
// BAD - the // comment breaks everything after it
const script = `
SET x TO 1.
// This breaks the script
SET y TO 2.
`.replaceAll('\n', ' ');
// Result: "SET x TO 1. // This breaks the script SET y TO 2."
// kOS sees only "SET x TO 1." - everything after // is a comment!
// GOOD - no comments inside kOS script
const script = `
SET x TO 1.
SET y TO 2.
`.replaceAll('\n', ' ');请在脚本字符串上方的TypeScript代码中添加解释性注释。
基于结果的民意调查
对于时间扭曲等长时间运行的操作,轮询实际结果比检查操作状态更可靠:
- SOI翘曲:民意调查
SHIP:BODY:NAME直到它改变(检测SOI交叉) - 节点扭曲:民意调查
NEXTNODE:ETA直到接近目标时间 - 轨道点扭曲:民意调查
ETA:PERIAPSIS或ETA:APOAPSIS
使用此模式是因为在高时间扭曲期间,kOS响应可能会延迟或不可靠。
基于标志的完成
对于节点执行等复杂操作:
- 设置kOS侧标志:
SET MCP_BURN_DONE TO FALSE. - 安装WHEN触发器:
WHEN NOT HASNODE THEN { SET MCP_BURN_DONE TO TRUE. } - 投票给国旗:
PRINT MCP_BURN_DONE.
时间扭曲命令
使用 KUNIVERSE:TIMEWARP:WARPTO() (非阻塞)而不是 WARPTO() (阻塞)以更好地控制经纱完成检测。
无线电停电处理
在无线电中断期间(船体后面,超出范围),kOS终端无法访问,档案文件也无法读取。ksp-mcp很好地处理了这个问题:
| 场景 | 处理程序 |
|---|---|
| 轮询过程中信号丢失 | pollWithBlackoutResilience 等待恢复 |
| 停电期间的节点执行 | MechJeb自主运行(在扭曲之前启用) |
| 停电中的闲置船只 | MCP守护进程自动扭曲为无线电联系 |
关键实施:
- 曲速前启用MechJeb:即使我们扭曲到黑暗中,燃烧也会完全自主
pollWithBlackoutResilience:在任何长时间运行的操作中,都能优雅地处理信号丢失- 本地脚本幸存下来:船舶本地存储中的脚本(
1:/)继续停电
MCP守护程序
MCP守护程序是一个kOS引导脚本,它提供了自主的断电恢复。它在船只的CPU上运行,处理船只在无线电中断时闲置的情况。
特性
- 心跳:更新
_MCP_HEARTBEAT健康监测的每一个物理指标 - 无线电状态:曲目
_MCP_RADIO当前信号状态 - 自动扭曲到收音机:在断电状态下空闲时(没有正在进行的操作),自动扭曲到下一个无线电联系窗口
- 运营跟踪:尊重
_MCP_OP标记以避免干扰正在进行的操作
自安装启动文件
守护进程是 自安装引导程序 在无线电中断后幸存下来:
- 部署:MCP将守护进程写入存档(
0:/boot/mcp_daemon.ks) - 首次运行:守护进程检测到它正在从存档中运行,将自身复制到本地卷(
1:/boot/mcp_daemon.ks),然后重新启动 - 重新启动后:kOS优先考虑本地
/boot/过度存档,因此本地副本会运行 - 停电生存:本地脚本在停电期间继续运行;存档脚本停止
Archive (0:/) Local (1:/)
│ │
▼ ▼
┌─────────────┐ ┌─────────────┐
│ mcp_daemon │──────▶│ mcp_daemon │ (self-installs on first run)
│ .ks │ copy │ .ks │
└─────────────┘ └─────────────┘
│
▼
Survives blackout守护进程状态
通过检查守护进程状态 status 工具或:
import { checkDaemonStatus } from 'ksp-mcp/daemon';
const status = await checkDaemonStatus(conn);
console.log(status.running); // Is daemon loop active?
console.log(status.version); // Version hash (e.g., "c3561fa5")
console.log(status.locallyInstalled); // Is local copy installed?
console.log(status.needsUpdate); // Does version mismatch?更新守护进程
部署新版本时:
- 新版本写入存档
- 旧的本地副本将继续运行,直到手动更新
- 要更新:删除本地副本并重新启动
DELETEPATH("1:/boot/mcp_daemon.ks").
REBOOT.然后,存档副本将自动安装新版本。
开发与调试
日志记录
ksp-mcp提供了两个用于调试的日志系统:
MCP日志文件
所有MCP工具消息(信息、警告、错误、进度、调试)都写入:
logs/ksp-mcp-.log日志格式:
[2026-01-19T12:34:56.789Z] INFO Mission started
[2026-01-19T12:34:57.123Z] PROGRESS [Launch] Ascending to 80km...
[2026-01-19T12:34:58.456Z] DEBUG [Launch] Poll timeout (1/3), retrying...
[2026-01-19T12:34:59.789Z] ERROR Connection lost自定义日志目录:
KSP_MCP_LOG_DIR=/tmp/my-logs npx ksp-mcp传输跟踪日志
对于低级套接字调试(原始kOS命令/响应):
KOS_TRACE=1 npx ksp-mcp写信给 logs/kos-trace-*.log 与:
SEND:发送到kOS的命令RECV:kOS的回应INFO:连接事件ERROR:传输错误
自定义目录: KOS_TRACE_DIR=/tmp/traces
测试阻塞操作
当测试可能阻塞的操作(如时间扭曲)时,请在后台进程中运行它们:
# Run a blocking test in background
node -e "
const { KosConnection } = require('./dist/transport/kos-connection.js');
const { warpTo } = require('./dist/mechjeb/programs/warp.js');
async function test() {
const conn = new KosConnection();
await conn.connect();
const result = await warpTo(conn, 'soi', { timeout: 300000 });
console.log('Result:', JSON.stringify(result, null, 2));
}
test().catch(console.error);
" &本底监测
测试运行时监视kOS状态:
# Monitor body, warp level, and SOI ETA every 2 seconds
node -e "
const { KosConnection } = require('./dist/transport/kos-connection.js');
async function monitor() {
const conn = new KosConnection();
await conn.connect();
setInterval(async () => {
const result = await conn.execute('PRINT SHIP:BODY:NAME + \"|\" + WARP.', 2000);
console.log(new Date().toISOString().substr(11,8), result.output.trim());
}, 2000);
}
monitor().catch(console.error);
" &这有助于调试在KSP中完成操作但检测失败的问题。
使用ksp-mcp REPL
对于交互式调试,请使用带有原始kOS命令的守护进程:
npm run daemon:start
npm run kos "PRINT SHIP:BODY:NAME."
npm run kos "PRINT WARP."
npm run kos "PRINT SHIP:ORBIT:HASNEXTPATCH."贡献:添加新工具
此项目维护MCP工具和CLI脚本之间的对等性。这两个接口都是围绕共享库函数的精简包装。
建筑
┌─────────────────────────────────────────────────────┐
│ CLI (stdio) │ MCP Server (stdio/http) │
│ - Parse args │ - Parse JSON-RPC │
│ - Format output │ - Format responses │
└───────────┬───────────┴───────────┬─────────────────┘
│ │
▼ ▼
┌─────────────────────────────────────────────────────┐
│ Shared Libraries │
│ - KosConnection - ManeuverProgram │
│ - AscentProgram - executeNode() │
│ - getShipTelemetry() - clearNodes() │
└─────────────────────────────────────────────────────┘添加新工具的步骤
- 实现库功能 在
src/mechjeb/programs/(或适当位置)
// src/mechjeb/programs/example.ts
export async function myOperation(conn: KosConnection, param: number): Promise {
// Implementation using conn.execute()
}- 添加MCP工具 在
src/server.ts
server.registerTool(
'my_operation', // Use snake_case for MCP tools
{
description: 'Does something useful',
inputSchema: { param: z.number() },
},
async (args) => {
const result = await myOperation(conn, args.param);
return result.success ? successResponse(...) : errorResponse(...);
}
);- 添加CLI脚本 在
src/cli/(使用与MCP名称匹配的烤肉串大小写)
// src/cli/my-operation.ts
import { KosConnection } from '../transport/kos-connection.js';
import { myOperation } from '../mechjeb/programs/example.js';
async function main() {
const conn = new KosConnection({ cpuLabel: 'guidance' });
await conn.connect();
const result = await myOperation(conn, parseInt(process.argv[2]));
console.log(result.success ? '✅ Done' : `❌ ${result.error}`);
await conn.disconnect();
}
main().catch(console.error);- 添加npm脚本 到
package.json
"my-operation": "tsx src/cli/my-operation.ts"- 验证奇偶校验 和
npm run check:parity
命名规范
| MCP工具(snake_case) | CLI脚本(kebab case) |
|---|---|
launch_ascent | launch-ascent |
hohmann_transfer | hohmann-transfer |
match_velocities | match-velocities |
许可证
麻省理工学院
