mirror of
https://github.com/MoonshotAI/kimi-code.git
synced 2026-08-26 09:05:46 +00:00
Some checks are pending
CI / build (push) Waiting to run
CI / test (1) (push) Waiting to run
CI / test (2) (push) Waiting to run
CI / test (3) (push) Waiting to run
CI / test (4) (push) Waiting to run
CI / test (5) (push) Waiting to run
CI / test-pi-tui (push) Waiting to run
CI / test-vscode-legacy (push) Waiting to run
CI / test-windows (push) Waiting to run
CI / lint (push) Waiting to run
CI / typecheck (push) Waiting to run
Nix Build / Check flake.nix workspace sync (push) Waiting to run
Nix Build / nix build .#kimi-code (push) Blocked by required conditions
Release / Release (push) Waiting to run
Release / Deploy docs (push) Blocked by required conditions
Release / Native release artifact (push) Blocked by required conditions
Release / Publish native release assets (push) Blocked by required conditions
* feat(agent-core-v2): add the unified MCP management plane Port the v1 MCP management plane (#2858) onto the v2 DI x Scope engine: - App-scope IMcpOAuthService shared by every workspace handler and session overlay: credential events, single-flight refresh, proactive refresh timers, OAuthTokenTransaction-serialized writes, offline tokenState, shutdown. Providers read tokens through the store so grants written or revoked by another process are honored immediately; http/sse transports ride the transaction fetch. - IMcpConfigStore: the single write point for the user-level mcp.json over the filesystem byte store, byte-identical to v1's format, with per-entry validation, name normalization, __proto__-safe parsing, a mutation tail, and an onDidWrite event. - IMcpRegistryService: the unified read view over the layered config files (with per-entry origins) and plugin manifests (full descriptors incl. disabled, with provenance); collisions stay visible and runtime resolution ranks an enabled plugin above the file layers. - IMcpManagementService: guarded CRUD, connection-test probes, the locator-addressed inspection/auth-status surface, and locator-addressed OAuth begin/complete/cancel/reset with ambiguity rejection. Engine services stay ungated; the mcp_management flag gates the edge exposure. - Workspace runtime aligns with v1 precedence (an enabled plugin entry wins over the file layers, shadows revive), and management writes reload immediately via onDidWrite instead of the watch debounce. - node-sdk v2 facade delegates to the engine service (deleting its in-process duplication); kap-server exposes /api/v2/mcp/* and klient gains global.mcp.*, both flag-gated. * fix(agent-core-v2): settle early and cancelled MCP OAuth callbacks * refactor(node-sdk): write session MCP persists through the engine config store * refactor(agent-core-v2): strip comments from the MCP management plane files * fix(agent-core-v2): harden MCP management readiness * test(node-sdk): cover offline MCP auth statuses * fix(agent-core-v2): isolate stdio MCP probes * fix(klient): normalize MCP OAuth errors * fix(mcp): honor workspace CRUD context and refresh timing * fix(mcp): drain OAuth refreshes during shutdown * fix(mcp): guard CRUD across registry collisions * fix(mcp): canonicalize trust and refresh scheduling * fix(mcp): close callback listener on setup failure * fix(mcp): preserve trust and oauth behavior * fix(oauth): retain refresh tokens after SDK saves * fix(oauth): stop proactive sweep during shutdown * fix: await MCP workspace reconciliation * fix: serialize MCP OAuth and trust cleanup * fix: reject persisted MCP plugin collisions * fix: reconcile MCP workspaces concurrently * fix(mcp): check project-layer trust at the queried cwd * fix(mcp): expire abandoned OAuth flows after an idle timeout * fix(mcp): keep mutable user entries writable past read-only collisions * fix(mcp): abort the auth::complete long poll on client disconnect * fix(mcp): map OAuth flow failures to wire code 40929 * docs(mcp): note probe credential effects and plane semantics * chore: add the SDK changeset for MCP management cwd params * feat(mcp): expose the management plane without the experimental flag * fix(mcp): preserve auth management semantics * fix(agent-core-v2): bound MCP OAuth auth-server requests and the shutdown drain * fix(node-sdk): restate engine MCP management errors as KimiError * fix(agent-core-v2): preserve shared OAuth flow lifetime * fix(agent-core-v2): close MCP OAuth cancellation and shutdown gaps - bound the authorization-code exchange with the request timeout and the flow/caller abort signals, and make shutdown abort hung begins and close their callback listeners immediately - keep token-transaction effect coalescing intact when durable tokens carry local stamps, and serialize the meta sidecar and tokens-saved event with the token write inside the lock - drain transport-driven grants, their trailing SDK save continuations, and interactive completions during shutdown, with a cancellable deadline * fix(agent-core-v2): harden MCP probe runtime resolution and path handling - resolve stdio probes against the containing workspace's runtimes and reject out-of-workspace probes for non-local runtime_id instead of silently falling back to a local-only transient registry - share one Windows-aware path canonicalization across the config loader, registry trust lookup, trust records, and workspace matching - keep a UTF-8 BOM fatal for the user-level mcp.json store, matching the workspace loader and v1 - validate completeServerAuth timeoutMs bounds at the engine boundary * fix(agent-core-v2): await workspace MCP reconciliation on plugin mutations Plugin install/enable/disable/remove now resolve only after reload listeners settle their waitUntil work, so a disabled plugin's MCP server cannot linger connected and an enabled one is visible to the next session, matching v1. The workspace MCP consumer joins the barrier while keeping its log-only failure tolerance; delivery is awaited outside the mutation queue to avoid self-deadlock through consumption reads. * fix(mcp): close the SDK, klient, and server edge gaps - register mcp.oauth_failed in the v1 error registry and restate unknown engine codes as internal instead of minting undeclared KimiError codes - route persisted session MCP adds through the same KimiError restating as the global management methods - give the klient IPC transport a per-call timeout so completeAuth's long poll outlives the 30s default, clamped to the Node timer ceiling, and align the contract timeoutMs upper bound with REST - await the MCP OAuth service shutdown directly in SDK and server close before scope disposal * fix(agent-core-v2): keep file-over-plugin MCP precedence and harden the plane - Revert the v1-style precedence flip: the workspace merge and resolveRuntimeTarget keep the file entry above plugins (v2's historical order; the divergence from v1 is deliberate and documented in AGENTS.md). - Guards follow each engine's winner: project-layer entries stay read-only, while plugin entries never block user-level writes, so a file entry may shadow a plugin and removing it revives the plugin. The parity suite pins the engine split for a persisted session add over a plugin-owned name. - inspectServers tolerates a wire-encoded null targets array: klient's ipc transport sends null for an omitted leading optional argument. - Fire the config store's onDidWrite after the mutation tail settles, so a write listener can re-enter the store without deadlocking the queue; concurrent-mutation and re-entrant-listener tests pin both contracts. * chore: condense the sdk MCP changeset to one sentence * test(node-sdk): pin verify:false auth-status parity and fix the sdk changeset
155 lines
5.9 KiB
TypeScript
155 lines
5.9 KiB
TypeScript
import { mkdtemp, rm } from 'node:fs/promises';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
|
|
import { afterEach, describe, expect, it } from 'vitest';
|
|
|
|
import { type RunningServer, startServer } from '../src/start';
|
|
import { TEST_HOST_IDENTITY } from './helpers/hostIdentity';
|
|
import { authHeaders } from './helpers/auth';
|
|
|
|
describe('server-v2 OpenAPI', () => {
|
|
let server: RunningServer | undefined;
|
|
let home: string | undefined;
|
|
|
|
afterEach(async () => {
|
|
if (server !== undefined) {
|
|
await server.close();
|
|
server = undefined;
|
|
}
|
|
if (home !== undefined) {
|
|
await rm(home, { recursive: true, force: true });
|
|
home = undefined;
|
|
}
|
|
});
|
|
|
|
async function fetchOpenApi(): Promise<Record<string, unknown>> {
|
|
home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-openapi-'));
|
|
server = await startServer({
|
|
hostIdentity: TEST_HOST_IDENTITY,
|
|
host: '127.0.0.1',
|
|
port: 0,
|
|
homeDir: home,
|
|
logLevel: 'silent',
|
|
});
|
|
const res = await fetch(`http://127.0.0.1:${server.port}/openapi.json`, {
|
|
headers: authHeaders(server),
|
|
} as never);
|
|
expect(res.status).toBe(200);
|
|
expect(res.headers.get('content-type')).toContain('application/json');
|
|
return (await res.json()) as Record<string, unknown>;
|
|
}
|
|
|
|
it('returns a valid OpenAPI 3 document', async () => {
|
|
const doc = await fetchOpenApi();
|
|
|
|
expect(doc['openapi']).toMatch(/^3\.\d+\.\d+$/);
|
|
const info = asRecord(doc['info']);
|
|
expect(info['title']).toBe('Kimi Code Server API');
|
|
expect(typeof info['version']).toBe('string');
|
|
});
|
|
|
|
it('covers the core /api/v1 routes v2 registers', async () => {
|
|
const doc = await fetchOpenApi();
|
|
const paths = asRecord(doc['paths']);
|
|
|
|
expect(paths['/api/v1/healthz']).toBeDefined();
|
|
expect(paths['/api/v1/meta']).toBeDefined();
|
|
expect(paths['/api/v1/sessions']).toBeDefined();
|
|
expect(paths['/api/v1/files']).toBeDefined();
|
|
expect(paths['/api/v1/sessions/{session_id}/fs/{*}']).toBeDefined();
|
|
});
|
|
|
|
it('projects the session-action dispatcher into archive only', async () => {
|
|
const doc = await fetchOpenApi();
|
|
const paths = asRecord(doc['paths']);
|
|
|
|
expect(paths['/api/v1/sessions/{tail}']).toBeUndefined();
|
|
expect(paths['/api/v1/sessions/{session_id}:archive']).toBeDefined();
|
|
expect(paths['/api/v1/sessions/{session_id}:fork']).toBeUndefined();
|
|
expect(paths['/api/v1/sessions/{session_id}:undo']).toBeUndefined();
|
|
|
|
const archiveOp = operation(doc, '/api/v1/sessions/{session_id}:archive', 'post');
|
|
expect(archiveOp['operationId']).toBe('runSessionArchiveAction');
|
|
const params = archiveOp['parameters'] as Array<Record<string, unknown>>;
|
|
expect(params.some((p) => p['in'] === 'path' && p['name'] === 'session_id')).toBe(true);
|
|
expect(params.some((p) => p['name'] === 'tail')).toBe(false);
|
|
});
|
|
|
|
it('describes the file upload as multipart/form-data', async () => {
|
|
const doc = await fetchOpenApi();
|
|
const uploadOp = operation(doc, '/api/v1/files', 'post');
|
|
const requestBody = asRecord(uploadOp['requestBody']);
|
|
const content = asRecord(requestBody['content']);
|
|
expect(content['multipart/form-data']).toBeDefined();
|
|
});
|
|
|
|
it('describes session export as a ZIP or JSON error envelope', async () => {
|
|
const doc = await fetchOpenApi();
|
|
const exportOp = operation(doc, '/api/v1/sessions/{session_id}/export', 'post');
|
|
const responses = asRecord(exportOp['responses']);
|
|
const response = asRecord(responses['200']);
|
|
const content = asRecord(response['content']);
|
|
const headers = asRecord(response['headers']);
|
|
const zipSchema = asRecord(asRecord(content['application/zip'])['schema']);
|
|
const errorSchema = asRecord(asRecord(content['application/json'])['schema']);
|
|
const errorProperties = asRecord(errorSchema['properties']);
|
|
|
|
expect(zipSchema).toMatchObject({ type: 'string', format: 'binary' });
|
|
expect(errorProperties).toMatchObject({
|
|
code: expect.any(Object),
|
|
msg: expect.any(Object),
|
|
data: expect.any(Object),
|
|
request_id: expect.any(Object),
|
|
});
|
|
expect(headers['content-disposition']).toBeDefined();
|
|
expect(headers['content-length']).toBeDefined();
|
|
expect(headers['cache-control']).toBeDefined();
|
|
});
|
|
|
|
it('represents the fs-action dispatcher as a oneOf union', async () => {
|
|
const doc = await fetchOpenApi();
|
|
const fsActionOp = operation(doc, '/api/v1/sessions/{session_id}/{tail}', 'post');
|
|
const requestBody = asRecord(fsActionOp['requestBody']);
|
|
const content = asRecord(requestBody['content']);
|
|
const json = asRecord(content['application/json']);
|
|
const schema = asRecord(json['schema']);
|
|
expect(Array.isArray(schema['oneOf'])).toBe(true);
|
|
});
|
|
|
|
it('documents MCP OAuth failures for auth completion', async () => {
|
|
const doc = await fetchOpenApi();
|
|
const authCompleteOp = operation(doc, '/api/v2/mcp/auth:complete', 'post');
|
|
const responses = asRecord(authCompleteOp['responses']);
|
|
const response = asRecord(responses['200']);
|
|
const content = asRecord(response['content']);
|
|
const schema = asRecord(asRecord(content['application/json'])['schema']);
|
|
const variants = schema['oneOf'];
|
|
|
|
expect(Array.isArray(variants)).toBe(true);
|
|
expect(
|
|
(variants as unknown[]).some((variant) => {
|
|
const properties = asRecord(asRecord(variant)['properties']);
|
|
const values = asRecord(properties['code'])['enum'];
|
|
return Array.isArray(values) && values.includes(40929);
|
|
}),
|
|
).toBe(true);
|
|
});
|
|
});
|
|
|
|
function asRecord(value: unknown): Record<string, unknown> {
|
|
if (typeof value !== 'object' || value === null) {
|
|
throw new Error('expected object');
|
|
}
|
|
return value as Record<string, unknown>;
|
|
}
|
|
|
|
function operation(
|
|
doc: Record<string, unknown>,
|
|
path: string,
|
|
method: string,
|
|
): Record<string, unknown> {
|
|
const paths = asRecord(doc['paths']);
|
|
const pathItem = asRecord(paths[path]);
|
|
return asRecord(pathItem[method]);
|
|
}
|