Compare commits
28 Commits
feat/docke
...
feat/creat
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97ade470df | ||
|
|
b25ff98374 | ||
|
|
22fe9c3435 | ||
| 72643fceda | |||
|
|
467357c2c6 | ||
| d6a80fc03d | |||
|
|
c07da826a0 | ||
|
|
0482944056 | ||
| 46e07e4515 | |||
|
|
b8c5cf718a | ||
|
|
a4fe5fdbe2 | ||
|
|
e1ed585e2a | ||
|
|
48fce7fe45 | ||
|
|
89b2b1b13d | ||
|
|
6da4ae495c | ||
|
|
9a67e51307 | ||
|
|
9e660140b3 | ||
|
|
d0a224e839 | ||
|
|
6161686441 | ||
|
|
3ee0dbe58e | ||
|
|
a520b9ff47 | ||
|
|
9c08faa8d2 | ||
|
|
dbb2fe63cd | ||
|
|
4d796e2aa7 | ||
|
|
7c07749580 | ||
|
|
09675f020f | ||
|
|
4b67a9cc15 | ||
|
|
1b8b886995 |
15
.dockerignore
Normal file
15
.dockerignore
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
node_modules
|
||||||
|
*/node_modules
|
||||||
|
**/node_modules
|
||||||
|
dist
|
||||||
|
**/dist
|
||||||
|
.git
|
||||||
|
.taskmaster
|
||||||
|
.claude
|
||||||
|
*.md
|
||||||
|
!pnpm-workspace.yaml
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
deploy/docker-compose.yml
|
||||||
|
src/cli
|
||||||
|
src/mcplocal
|
||||||
142
.gitea/workflows/ci.yml
Normal file
142
.gitea/workflows/ci.yml
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
lint:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: 9
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
cache: pnpm
|
||||||
|
|
||||||
|
- run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: Lint
|
||||||
|
run: pnpm lint
|
||||||
|
|
||||||
|
typecheck:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: 9
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
cache: pnpm
|
||||||
|
|
||||||
|
- run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: Generate Prisma client
|
||||||
|
run: pnpm --filter @mcpctl/db exec prisma generate
|
||||||
|
|
||||||
|
- name: Typecheck
|
||||||
|
run: pnpm typecheck
|
||||||
|
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: 9
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
cache: pnpm
|
||||||
|
|
||||||
|
- run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: Generate Prisma client
|
||||||
|
run: pnpm --filter @mcpctl/db exec prisma generate
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
run: pnpm test:run
|
||||||
|
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [lint, typecheck, test]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: 9
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
cache: pnpm
|
||||||
|
|
||||||
|
- run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: Generate Prisma client
|
||||||
|
run: pnpm --filter @mcpctl/db exec prisma generate
|
||||||
|
|
||||||
|
- name: Build all packages
|
||||||
|
run: pnpm build
|
||||||
|
|
||||||
|
package:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [build]
|
||||||
|
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: 9
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
cache: pnpm
|
||||||
|
|
||||||
|
- run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: Generate Prisma client
|
||||||
|
run: pnpm --filter @mcpctl/db exec prisma generate
|
||||||
|
|
||||||
|
- name: Build TypeScript
|
||||||
|
run: pnpm build
|
||||||
|
|
||||||
|
- name: Install bun
|
||||||
|
uses: oven-sh/setup-bun@v2
|
||||||
|
|
||||||
|
- name: Install nfpm
|
||||||
|
run: |
|
||||||
|
curl -sL -o /tmp/nfpm.tar.gz "https://github.com/goreleaser/nfpm/releases/download/v2.45.0/nfpm_2.45.0_Linux_x86_64.tar.gz"
|
||||||
|
tar xzf /tmp/nfpm.tar.gz -C /usr/local/bin nfpm
|
||||||
|
|
||||||
|
- name: Bundle standalone binary
|
||||||
|
run: bun build src/cli/src/index.ts --compile --outfile dist/mcpctl
|
||||||
|
|
||||||
|
- name: Build RPM
|
||||||
|
run: nfpm pkg --packager rpm --target dist/
|
||||||
|
|
||||||
|
- name: Publish to Gitea packages
|
||||||
|
env:
|
||||||
|
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||||
|
run: |
|
||||||
|
RPM_FILE=$(ls dist/mcpctl-*.rpm | head -1)
|
||||||
|
curl --fail -X PUT \
|
||||||
|
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||||
|
--upload-file "$RPM_FILE" \
|
||||||
|
"${{ github.server_url }}/api/packages/${{ github.repository_owner }}/rpm/upload"
|
||||||
272
.taskmaster/docs/prd-v2-architecture.md
Normal file
272
.taskmaster/docs/prd-v2-architecture.md
Normal file
@@ -0,0 +1,272 @@
|
|||||||
|
# mcpctl v2 - Corrected 3-Tier Architecture PRD
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
mcpctl is a kubectl-inspired system for managing MCP (Model Context Protocol) servers. It consists of 4 components arranged in a 3-tier architecture:
|
||||||
|
|
||||||
|
```
|
||||||
|
Claude Code
|
||||||
|
|
|
||||||
|
v (stdio - MCP protocol)
|
||||||
|
mcplocal (Local Daemon - runs on developer machine)
|
||||||
|
|
|
||||||
|
v (HTTP REST)
|
||||||
|
mcpd (External Daemon - runs on server/NAS)
|
||||||
|
|
|
||||||
|
v (Docker API / K8s API)
|
||||||
|
mcp_servers (MCP server containers)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Components
|
||||||
|
|
||||||
|
### 1. mcpctl (CLI Tool)
|
||||||
|
- **Package**: `src/cli/` (`@mcpctl/cli`)
|
||||||
|
- **What it is**: kubectl-like CLI for managing the entire system
|
||||||
|
- **Talks to**: mcplocal (local daemon) via HTTP REST
|
||||||
|
- **Key point**: mcpctl does NOT talk to mcpd directly. It always goes through mcplocal.
|
||||||
|
- **Distributed as**: RPM package via Gitea registry (bun compile + nfpm)
|
||||||
|
- **Commands**: get, describe, apply, setup, instance, claude, project, backup, restore, config, status
|
||||||
|
|
||||||
|
### 2. mcplocal (Local Daemon)
|
||||||
|
- **Package**: `src/local-proxy/` (rename to `src/mcplocal/`)
|
||||||
|
- **What it is**: Local daemon running on the developer's machine
|
||||||
|
- **Talks to**: mcpd (external daemon) via HTTP REST
|
||||||
|
- **Exposes to Claude**: MCP protocol via stdio (tools, resources, prompts)
|
||||||
|
- **Exposes to mcpctl**: HTTP REST API for management commands
|
||||||
|
|
||||||
|
**Core responsibility: LLM Pre-processing**
|
||||||
|
|
||||||
|
This is the intelligence layer. When Claude asks for data from MCP servers, mcplocal:
|
||||||
|
|
||||||
|
1. Receives Claude's request (e.g., "get Slack messages about security")
|
||||||
|
2. Uses a local/cheap LLM (Gemini CLI binary, Ollama, vLLM, DeepSeek API) to interpret what Claude actually wants
|
||||||
|
3. Sends narrow, filtered requests to mcpd which forwards to the actual MCP servers
|
||||||
|
4. Receives raw results from MCP servers (via mcpd)
|
||||||
|
5. Uses the local LLM again to filter/summarize results - extracting only what's relevant
|
||||||
|
6. Returns the smallest, most comprehensive response to Claude
|
||||||
|
|
||||||
|
**Why**: Claude Code tokens are expensive. Instead of dumping 500 Slack messages into Claude's context window, mcplocal uses a cheap LLM to pre-filter to the 12 relevant ones.
|
||||||
|
|
||||||
|
**LLM Provider Strategy** (already partially exists):
|
||||||
|
- Gemini CLI binary (local, free)
|
||||||
|
- Ollama (local, free)
|
||||||
|
- vLLM (local, free)
|
||||||
|
- DeepSeek API (cheap)
|
||||||
|
- OpenAI API (fallback)
|
||||||
|
- Anthropic API (fallback)
|
||||||
|
|
||||||
|
**Additional mcplocal responsibilities**:
|
||||||
|
- MCP protocol routing (namespace tools: `slack/send_message`, `jira/create_issue`)
|
||||||
|
- Connection health monitoring for upstream MCP servers
|
||||||
|
- Caching frequently requested data
|
||||||
|
- Proxying mcpctl management commands to mcpd
|
||||||
|
|
||||||
|
### 3. mcpd (External Daemon)
|
||||||
|
- **Package**: `src/mcpd/` (`@mcpctl/mcpd`)
|
||||||
|
- **What it is**: Server-side daemon that runs on centralized infrastructure (Synology NAS, cloud server, etc.)
|
||||||
|
- **Deployed via**: Docker Compose (Dockerfile + docker-compose.yml)
|
||||||
|
- **Database**: PostgreSQL for state, audit logs, access control
|
||||||
|
|
||||||
|
**Core responsibilities**:
|
||||||
|
- **Deploy and run MCP server containers** (Docker now, Kubernetes later)
|
||||||
|
- **Instance lifecycle management**: start, stop, restart, logs, inspect
|
||||||
|
- **MCP server registry**: Store server definitions, configuration templates, profiles
|
||||||
|
- **Project management**: Group MCP profiles into projects for Claude sessions
|
||||||
|
- **Auditing**: Log every operation - who ran what, when, with what result
|
||||||
|
- **Access management**: Users, sessions, permissions - who can access which MCP servers
|
||||||
|
- **Credential storage**: MCP servers often need API tokens (Slack, Jira, GitHub) - stored securely on server side, never exposed to local machine
|
||||||
|
- **Backup/restore**: Export and import configuration
|
||||||
|
|
||||||
|
**Key point**: mcpd holds the credentials. When mcplocal asks mcpd to query Slack, mcpd runs the Slack MCP server container with the proper SLACK_TOKEN injected - mcplocal never sees the token.
|
||||||
|
|
||||||
|
### 4. mcp_servers (MCP Server Containers)
|
||||||
|
- **What they are**: The actual MCP server processes (Slack, Jira, GitHub, Terraform, filesystem, postgres, etc.)
|
||||||
|
- **Managed by**: mcpd via Docker/Podman API
|
||||||
|
- **Network**: Isolated network, only accessible by mcpd
|
||||||
|
- **Credentials**: Injected by mcpd as environment variables
|
||||||
|
- **Communication**: MCP protocol (stdio or SSE/HTTP) between mcpd and the containers
|
||||||
|
|
||||||
|
## Data Flow Examples
|
||||||
|
|
||||||
|
### Example 1: Claude asks for Slack messages
|
||||||
|
```
|
||||||
|
Claude: "Get messages about security incidents from the last week"
|
||||||
|
|
|
||||||
|
v (MCP tools/call: slack/search_messages)
|
||||||
|
mcplocal:
|
||||||
|
1. Intercepts the tool call
|
||||||
|
2. Calls local Gemini: "User wants security incident messages from last week.
|
||||||
|
Generate optimal Slack search query and date filters."
|
||||||
|
3. Gemini returns: query="security incident OR vulnerability OR CVE", after="2024-01-15"
|
||||||
|
4. Sends filtered request to mcpd
|
||||||
|
|
|
||||||
|
v (HTTP POST /api/v1/mcp/proxy)
|
||||||
|
mcpd:
|
||||||
|
1. Looks up Slack MCP instance (injects SLACK_TOKEN)
|
||||||
|
2. Forwards narrowed query to Slack MCP server container
|
||||||
|
3. Returns raw results (200 messages)
|
||||||
|
|
|
||||||
|
v (response)
|
||||||
|
mcplocal:
|
||||||
|
1. Receives 200 messages
|
||||||
|
2. Calls local Gemini: "Filter these 200 Slack messages. Keep only those
|
||||||
|
directly about security incidents. Return message IDs and 1-line summaries."
|
||||||
|
3. Gemini returns: 15 relevant messages with summaries
|
||||||
|
4. Returns filtered result to Claude
|
||||||
|
|
|
||||||
|
v (MCP response: 15 messages instead of 200)
|
||||||
|
Claude: processes only the relevant 15 messages
|
||||||
|
```
|
||||||
|
|
||||||
|
### Example 2: mcpctl management command
|
||||||
|
```
|
||||||
|
$ mcpctl get servers
|
||||||
|
|
|
||||||
|
v (HTTP GET)
|
||||||
|
mcplocal:
|
||||||
|
1. Recognizes this is a management command (not MCP data)
|
||||||
|
2. Proxies directly to mcpd (no LLM processing needed)
|
||||||
|
|
|
||||||
|
v (HTTP GET /api/v1/servers)
|
||||||
|
mcpd:
|
||||||
|
1. Queries PostgreSQL for server definitions
|
||||||
|
2. Returns list
|
||||||
|
|
|
||||||
|
v (proxied response)
|
||||||
|
mcplocal -> mcpctl -> formatted table output
|
||||||
|
```
|
||||||
|
|
||||||
|
### Example 3: mcpctl instance management
|
||||||
|
```
|
||||||
|
$ mcpctl instance start slack
|
||||||
|
|
|
||||||
|
v
|
||||||
|
mcplocal -> mcpd:
|
||||||
|
1. Creates Docker container for Slack MCP server
|
||||||
|
2. Injects SLACK_TOKEN from secure storage
|
||||||
|
3. Connects to isolated mcp-servers network
|
||||||
|
4. Logs audit entry: "user X started slack instance"
|
||||||
|
5. Returns instance status
|
||||||
|
```
|
||||||
|
|
||||||
|
## What Already Exists (completed work)
|
||||||
|
|
||||||
|
### Done and reusable as-is:
|
||||||
|
- Project structure: pnpm monorepo, TypeScript strict mode, Vitest, ESLint
|
||||||
|
- Database schema: Prisma + PostgreSQL (User, McpServer, McpProfile, Project, McpInstance, AuditLog)
|
||||||
|
- mcpd server framework: Fastify 5, routes, services, repositories, middleware
|
||||||
|
- mcpd MCP server CRUD: registration, profiles, projects
|
||||||
|
- mcpd Docker container management: dockerode, instance lifecycle
|
||||||
|
- mcpd audit logging, health monitoring, metrics, backup/restore
|
||||||
|
- mcpctl CLI framework: Commander.js, commands, config, API client, formatters
|
||||||
|
- mcpctl RPM distribution: bun compile, nfpm, Gitea publishing, shell completions
|
||||||
|
- MCP protocol routing in local-proxy: namespace tools, resources, prompts
|
||||||
|
- LLM provider abstractions: OpenAI, Anthropic, Ollama adapters (defined but unused)
|
||||||
|
- Shared types and profile templates
|
||||||
|
|
||||||
|
### Needs rework:
|
||||||
|
- mcpctl currently talks to mcpd directly -> must talk to mcplocal instead
|
||||||
|
- local-proxy is just a dumb router -> needs LLM pre-processing intelligence
|
||||||
|
- local-proxy has no HTTP API for mcpctl -> needs REST endpoints for management proxying
|
||||||
|
- mcpd has no MCP proxy endpoint -> needs endpoint that mcplocal can call to execute MCP tool calls on managed instances
|
||||||
|
- No integration between LLM providers and MCP request/response pipeline
|
||||||
|
|
||||||
|
## New Tasks Needed
|
||||||
|
|
||||||
|
### Phase 1: Rename and restructure local-proxy -> mcplocal
|
||||||
|
- Rename `src/local-proxy/` to `src/mcplocal/`
|
||||||
|
- Update all package references and imports
|
||||||
|
- Add HTTP REST server (Fastify) alongside existing stdio server
|
||||||
|
- mcplocal needs TWO interfaces: stdio for Claude, HTTP for mcpctl
|
||||||
|
|
||||||
|
### Phase 2: mcplocal management proxy
|
||||||
|
- Add REST endpoints that mirror mcpd's API (get servers, instances, projects, etc.)
|
||||||
|
- mcpctl config changes: `daemonUrl` now points to mcplocal (e.g., localhost:3200) instead of mcpd
|
||||||
|
- mcplocal proxies management requests to mcpd (configurable `mcpdUrl` e.g., http://nas:3100)
|
||||||
|
- Pass-through with no LLM processing for management commands
|
||||||
|
|
||||||
|
### Phase 3: mcpd MCP proxy endpoint
|
||||||
|
- Add `/api/v1/mcp/proxy` endpoint to mcpd
|
||||||
|
- Accepts: `{ serverId, method, params }` - execute an MCP tool call on a managed instance
|
||||||
|
- mcpd looks up the instance, connects to the container, executes the MCP call, returns result
|
||||||
|
- This is how mcplocal talks to MCP servers without needing direct Docker access
|
||||||
|
|
||||||
|
### Phase 4: LLM pre-processing pipeline in mcplocal
|
||||||
|
- Create request interceptor in mcplocal's MCP router
|
||||||
|
- Before forwarding `tools/call` to mcpd, run the request through LLM for interpretation
|
||||||
|
- After receiving response from mcpd, run through LLM for filtering/summarization
|
||||||
|
- LLM provider selection based on config (prefer local/cheap models)
|
||||||
|
- Configurable: enable/disable pre-processing per server or per tool
|
||||||
|
- Bypass for simple operations (list, create, delete - no filtering needed)
|
||||||
|
|
||||||
|
### Phase 5: Smart context optimization
|
||||||
|
- Token counting: estimate how many tokens the raw response would consume
|
||||||
|
- Decision logic: if raw response < threshold, skip LLM filtering (not worth the latency)
|
||||||
|
- If raw response > threshold, filter with LLM
|
||||||
|
- Cache LLM filtering decisions for repeated similar queries
|
||||||
|
- Metrics: track tokens saved, latency added by filtering
|
||||||
|
|
||||||
|
### Phase 6: mcpctl -> mcplocal migration
|
||||||
|
- Update mcpctl's default daemonUrl to point to mcplocal (localhost:3200)
|
||||||
|
- Update all CLI commands to work through mcplocal proxy
|
||||||
|
- Add `mcpctl config set mcpd-url <url>` for configuring upstream mcpd
|
||||||
|
- Add `mcpctl config set mcplocal-url <url>` for configuring local daemon
|
||||||
|
- Health check: `mcpctl status` shows both mcplocal and mcpd connectivity
|
||||||
|
- Shell completions update if needed
|
||||||
|
|
||||||
|
### Phase 7: End-to-end integration testing
|
||||||
|
- Test full flow: mcpctl -> mcplocal -> mcpd -> mcp_server -> response -> LLM filter -> Claude
|
||||||
|
- Test management commands pass through correctly
|
||||||
|
- Test LLM pre-processing reduces context window size
|
||||||
|
- Test credential isolation (mcplocal never sees MCP server credentials)
|
||||||
|
- Test health monitoring across all tiers
|
||||||
|
|
||||||
|
## Authentication & Authorization
|
||||||
|
|
||||||
|
### Database ownership
|
||||||
|
- **mcpd owns the database** (PostgreSQL). It is the only component that talks to the DB.
|
||||||
|
- mcplocal has NO database. It is stateless (config file only).
|
||||||
|
- mcpctl has NO database. It stores user credentials locally in `~/.mcpctl/config.yaml`.
|
||||||
|
|
||||||
|
### Auth flow
|
||||||
|
```
|
||||||
|
mcpctl login
|
||||||
|
|
|
||||||
|
v (user enters mcpd URL + credentials)
|
||||||
|
mcpctl stores API token in ~/.mcpctl/config.yaml
|
||||||
|
|
|
||||||
|
v (passes token to mcplocal config)
|
||||||
|
mcplocal authenticates to mcpd using Bearer token on every request
|
||||||
|
|
|
||||||
|
v (Authorization: Bearer <token>)
|
||||||
|
mcpd validates token against Session table in PostgreSQL
|
||||||
|
|
|
||||||
|
v (authenticated request proceeds)
|
||||||
|
```
|
||||||
|
|
||||||
|
### mcpctl responsibilities
|
||||||
|
- `mcpctl login` command: prompts user for mcpd URL and credentials (username/password or API token)
|
||||||
|
- `mcpctl login` calls mcpd's auth endpoint to get a session token
|
||||||
|
- Stores the token in `~/.mcpctl/config.yaml` (or `~/.mcpctl/credentials` with restricted permissions)
|
||||||
|
- Passes the token to mcplocal (either via config or as startup argument)
|
||||||
|
- `mcpctl logout` command: invalidates the session token
|
||||||
|
|
||||||
|
### mcplocal responsibilities
|
||||||
|
- Reads auth token from its config (set by mcpctl)
|
||||||
|
- Attaches `Authorization: Bearer <token>` header to ALL requests to mcpd
|
||||||
|
- If mcpd returns 401, mcplocal returns appropriate error to mcpctl/Claude
|
||||||
|
- Does NOT store credentials itself - they come from mcpctl's config
|
||||||
|
|
||||||
|
### mcpd responsibilities
|
||||||
|
- Owns User and Session tables
|
||||||
|
- Provides auth endpoints: `POST /api/v1/auth/login`, `POST /api/v1/auth/logout`
|
||||||
|
- Validates Bearer tokens on every request via auth middleware (already exists)
|
||||||
|
- Returns 401 for invalid/expired tokens
|
||||||
|
- Audit logs include the authenticated user
|
||||||
|
|
||||||
|
## Non-functional Requirements
|
||||||
|
- mcplocal must start fast (developer's machine, runs per-session or as daemon)
|
||||||
|
- LLM pre-processing must not add more than 2-3 seconds latency
|
||||||
|
- If local LLM is unavailable, fall back to passing data through unfiltered
|
||||||
|
- All components must be independently deployable and testable
|
||||||
|
- mcpd must remain stateless (outside of DB) and horizontally scalable
|
||||||
@@ -307,7 +307,7 @@
|
|||||||
"dependencies": [
|
"dependencies": [
|
||||||
"4"
|
"4"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": [
|
"subtasks": [
|
||||||
{
|
{
|
||||||
"id": 1,
|
"id": 1,
|
||||||
@@ -367,7 +367,8 @@
|
|||||||
"testStrategy": "Run full integration test suite. Verify coverage >85% for project-related files.",
|
"testStrategy": "Run full integration test suite. Verify coverage >85% for project-related files.",
|
||||||
"parentId": "undefined"
|
"parentId": "undefined"
|
||||||
}
|
}
|
||||||
]
|
],
|
||||||
|
"updatedAt": "2026-02-21T04:30:43.622Z"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "6",
|
"id": "6",
|
||||||
@@ -380,7 +381,7 @@
|
|||||||
"3",
|
"3",
|
||||||
"4"
|
"4"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": [
|
"subtasks": [
|
||||||
{
|
{
|
||||||
"id": 1,
|
"id": 1,
|
||||||
@@ -465,7 +466,8 @@
|
|||||||
"testStrategy": "Unit tests for getLogs. Integration test: run container, tail logs, verify output.",
|
"testStrategy": "Unit tests for getLogs. Integration test: run container, tail logs, verify output.",
|
||||||
"parentId": "undefined"
|
"parentId": "undefined"
|
||||||
}
|
}
|
||||||
]
|
],
|
||||||
|
"updatedAt": "2026-02-21T04:52:51.544Z"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "7",
|
"id": "7",
|
||||||
@@ -514,8 +516,9 @@
|
|||||||
"dependencies": [
|
"dependencies": [
|
||||||
"7"
|
"7"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": []
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T04:55:53.675Z"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "9",
|
"id": "9",
|
||||||
@@ -528,8 +531,9 @@
|
|||||||
"7",
|
"7",
|
||||||
"4"
|
"4"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": []
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T05:14:48.368Z"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "10",
|
"id": "10",
|
||||||
@@ -542,8 +546,9 @@
|
|||||||
"7",
|
"7",
|
||||||
"5"
|
"5"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": []
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T05:17:02.390Z"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "11",
|
"id": "11",
|
||||||
@@ -555,8 +560,9 @@
|
|||||||
"dependencies": [
|
"dependencies": [
|
||||||
"1"
|
"1"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": []
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T05:00:28.388Z"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "12",
|
"id": "12",
|
||||||
@@ -568,8 +574,74 @@
|
|||||||
"dependencies": [
|
"dependencies": [
|
||||||
"11"
|
"11"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": []
|
"subtasks": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "Create main.ts entry point with configuration loading",
|
||||||
|
"description": "Implement the main.ts entry point that reads proxy configuration from file or CLI arguments, initializes upstreams based on config, and boots the StdioProxyServer.",
|
||||||
|
"dependencies": [],
|
||||||
|
"details": "Create src/local-proxy/src/main.ts that: 1) Parses command-line arguments (--config flag for JSON config path, or individual --upstream flags), 2) Loads ProxyConfig from JSON file if specified, 3) Instantiates StdioUpstream or HttpUpstream for each UpstreamConfig based on transport type, 4) Calls start() on each StdioUpstream to spawn child processes, 5) Adds all upstreams to McpRouter via addUpstream(), 6) Creates StdioProxyServer with the router and calls start(), 7) Handles SIGTERM/SIGINT for graceful shutdown calling router.closeAll(). Use a simple arg parser or process.argv directly. Export a main() function and call it when run directly.",
|
||||||
|
"status": "done",
|
||||||
|
"testStrategy": "Test config file loading with valid/invalid JSON. Test CLI argument parsing. Integration test: spawn proxy with mock upstream config and verify it starts and responds to initialize request.",
|
||||||
|
"parentId": "undefined",
|
||||||
|
"updatedAt": "2026-02-21T05:05:48.624Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "Add resource forwarding support to McpRouter",
|
||||||
|
"description": "Extend McpRouter to handle resources/list and resources/read methods, forwarding them to upstream servers with proper namespacing similar to tools.",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"details": "Modify src/local-proxy/src/router.ts to: 1) Add a resourceToServer Map similar to toolToServer, 2) Create discoverResources() method that calls resources/list on each upstream and aggregates results with namespaced URIs (e.g., 'servername://resource'), 3) Add 'resources' to capabilities in initialize response, 4) Handle 'resources/list' in route() by calling discoverResources(), 5) Handle 'resources/read' by parsing the namespaced URI, extracting server name, stripping prefix, and forwarding to correct upstream, 6) Handle 'resources/subscribe' and 'resources/unsubscribe' if needed for completeness. Update types.ts if additional resource-related types are needed.",
|
||||||
|
"status": "done",
|
||||||
|
"testStrategy": "Unit test discoverResources() with mocked upstreams returning different resources. Test resources/read routing extracts correct server and forwards properly. Test error handling when resource URI has unknown server prefix.",
|
||||||
|
"parentId": "undefined",
|
||||||
|
"updatedAt": "2026-02-21T05:05:48.626Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "Add prompt forwarding support to McpRouter",
|
||||||
|
"description": "Extend McpRouter to handle prompts/list and prompts/get methods, forwarding them to upstream servers with proper namespacing.",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"details": "Modify src/local-proxy/src/router.ts to: 1) Add a promptToServer Map for tracking prompt origins, 2) Create discoverPrompts() method that calls prompts/list on each upstream and aggregates with namespaced names (e.g., 'servername/prompt-name'), 3) Add 'prompts' to capabilities in initialize response, 4) Handle 'prompts/list' in route() by calling discoverPrompts(), 5) Handle 'prompts/get' by parsing namespaced prompt name, extracting server, stripping prefix, and forwarding to correct upstream. Follow same pattern as tools for consistency.",
|
||||||
|
"status": "done",
|
||||||
|
"testStrategy": "Unit test discoverPrompts() with mocked upstreams. Test prompts/get routing correctly forwards to upstream. Test error handling for unknown prompt names.",
|
||||||
|
"parentId": "undefined",
|
||||||
|
"updatedAt": "2026-02-21T05:05:48.638Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "Implement notification forwarding from upstreams to client",
|
||||||
|
"description": "Add support for forwarding JSON-RPC notifications from upstream servers to the proxy client, enabling real-time updates like progress notifications.",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"details": "Modify upstream classes and server: 1) Add onNotification callback to UpstreamConnection interface in types.ts, 2) Update StdioUpstream to detect notifications (messages without 'id' field) in stdout handler and invoke onNotification callback with namespaced method if needed, 3) Update HttpUpstream if SSE support is needed (may require EventSource or SSE client for true streaming), 4) Add setNotificationHandler(callback) method to McpRouter that registers handler and wires it to all upstreams, 5) Update StdioProxyServer to call router.setNotificationHandler() with a function that writes notification JSON to stdout, 6) Consider namespacing notification params to indicate source server.",
|
||||||
|
"status": "done",
|
||||||
|
"testStrategy": "Test StdioUpstream correctly identifies and forwards notifications. Integration test: upstream sends progress notification, verify proxy forwards it to stdout. Test notifications are properly namespaced with source server name.",
|
||||||
|
"parentId": "undefined",
|
||||||
|
"updatedAt": "2026-02-21T05:05:48.641Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"title": "Implement connection health monitoring with reconnection",
|
||||||
|
"description": "Add health monitoring for upstream connections with automatic status tracking, health check pings, and reconnection logic for failed STDIO upstreams.",
|
||||||
|
"dependencies": [
|
||||||
|
1,
|
||||||
|
4
|
||||||
|
],
|
||||||
|
"details": "Create src/local-proxy/src/health.ts with HealthMonitor class: 1) Track connection state for each upstream (healthy, degraded, disconnected), 2) Implement periodic health checks using ping/pong or a lightweight method like calling initialize, 3) Emit health status change events via EventEmitter pattern, 4) Add reconnection logic for StdioUpstream: detect process exit, attempt restart with exponential backoff (1s, 2s, 4s... max 30s), 5) Update McpRouter to accept HealthMonitor instance and use it to filter available upstreams, 6) Add health status to proxy logs/stderr for debugging, 7) Optionally expose health status via a special proxy method (e.g., 'proxy/health'). Update main.ts to instantiate and wire HealthMonitor.",
|
||||||
|
"status": "done",
|
||||||
|
"testStrategy": "Test health check detects unresponsive upstream. Test reconnection attempts with mocked process that fails then succeeds. Test exponential backoff timing. Test degraded upstream is excluded from tool discovery until healthy.",
|
||||||
|
"parentId": "undefined",
|
||||||
|
"updatedAt": "2026-02-21T05:05:48.643Z"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"updatedAt": "2026-02-21T05:05:48.643Z"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "13",
|
"id": "13",
|
||||||
@@ -581,8 +653,9 @@
|
|||||||
"dependencies": [
|
"dependencies": [
|
||||||
"12"
|
"12"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": []
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T05:22:44.011Z"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "14",
|
"id": "14",
|
||||||
@@ -594,8 +667,9 @@
|
|||||||
"dependencies": [
|
"dependencies": [
|
||||||
"3"
|
"3"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": []
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T05:09:18.694Z"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "15",
|
"id": "15",
|
||||||
@@ -607,8 +681,71 @@
|
|||||||
"dependencies": [
|
"dependencies": [
|
||||||
"4"
|
"4"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": []
|
"subtasks": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "Define Profile Template Types and Schemas",
|
||||||
|
"description": "Create TypeScript interfaces and Zod validation schemas for profile templates that extend the existing McpProfile type.",
|
||||||
|
"dependencies": [],
|
||||||
|
"details": "Create src/shared/src/profiles/types.ts with ProfileTemplate interface containing: id, serverType, name, displayName, description, category (filesystem/database/integration/etc), command, args, requiredEnvVars (with EnvTemplateEntry array), optionalEnvVars, defaultPermissions, setupInstructions, and documentationUrl. Also create profileTemplateSchema.ts with Zod schemas for validation. The templates should be immutable definitions that can be instantiated into actual profiles.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Unit test Zod schemas with valid and invalid template data. Verify type compatibility with existing McpServerConfig and McpProfile types.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "Implement Common MCP Server Profile Templates",
|
||||||
|
"description": "Create profile template definitions for common MCP servers including filesystem, github, postgres, slack, and other popular integrations.",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"details": "Create src/shared/src/profiles/templates/ directory with individual template files: filesystem.ts (npx @modelcontextprotocol/server-filesystem with path args), github.ts (npx @modelcontextprotocol/server-github with GITHUB_TOKEN env), postgres.ts (npx @modelcontextprotocol/server-postgres with DATABASE_URL), slack.ts (npx @modelcontextprotocol/server-slack with SLACK_TOKEN), memory.ts, and fetch.ts. Each template exports a ProfileTemplate constant with pre-configured best-practice settings. Include clear descriptions and setup guides for each.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Validate each template against the ProfileTemplate Zod schema. Verify all required fields are populated. Test that commands and args are syntactically correct.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "Build Profile Registry with Lookup and Filtering",
|
||||||
|
"description": "Create a profile registry that aggregates all templates and provides lookup, filtering, and search capabilities.",
|
||||||
|
"dependencies": [
|
||||||
|
1,
|
||||||
|
2
|
||||||
|
],
|
||||||
|
"details": "Create src/shared/src/profiles/registry.ts implementing a ProfileRegistry class with methods: getAll(), getById(id), getByCategory(category), getByServerType(type), search(query), and getCategories(). The registry should be a singleton that lazily loads all templates from the templates directory. Export a default registry instance. Also create src/shared/src/profiles/index.ts to export all profile-related types, templates, and the registry.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test registry initialization loads all templates. Test each lookup method returns correct results. Test search functionality with partial matches. Verify no duplicate IDs across templates.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "Add Profile Validation and Instantiation Utilities",
|
||||||
|
"description": "Create utility functions to validate profile templates and instantiate them into concrete profile configurations.",
|
||||||
|
"dependencies": [
|
||||||
|
1,
|
||||||
|
3
|
||||||
|
],
|
||||||
|
"details": "Create src/shared/src/profiles/utils.ts with functions: validateTemplate(template) - validates a ProfileTemplate against schema, instantiateProfile(templateId, envValues) - creates a concrete profile config from a template by filling in env vars, validateEnvValues(template, envValues) - checks if all required env vars are provided, getMissingEnvVars(template, envValues) - returns list of missing required env vars, and generateMcpJsonEntry(profile) - converts instantiated profile to .mcp.json format entry.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test validateTemplate with valid and invalid templates. Test instantiateProfile produces correct configs. Test env validation catches missing required vars. Test .mcp.json output matches expected format.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"title": "Export Profiles Module and Add Integration Tests",
|
||||||
|
"description": "Export the profiles module from shared package main entry and create comprehensive integration tests.",
|
||||||
|
"dependencies": [
|
||||||
|
3,
|
||||||
|
4
|
||||||
|
],
|
||||||
|
"details": "Update src/shared/src/index.ts to add 'export * from ./profiles/index.js'. Create src/shared/src/profiles/__tests__/profiles.test.ts with tests covering: all templates are valid, registry contains expected templates, instantiation works for each template type, .mcp.json generation produces valid output, and round-trip validation (instantiate then validate). Also add documentation comments to all exported functions and types.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Run full test suite with vitest. Verify exports are accessible from @mcpctl/shared. Integration test the full workflow: lookup template, validate, instantiate with env vars, generate .mcp.json entry.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"updatedAt": "2026-02-21T05:26:02.010Z"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "16",
|
"id": "16",
|
||||||
@@ -620,8 +757,9 @@
|
|||||||
"dependencies": [
|
"dependencies": [
|
||||||
"6"
|
"6"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": []
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T05:11:52.795Z"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "17",
|
"id": "17",
|
||||||
@@ -633,8 +771,70 @@
|
|||||||
"dependencies": [
|
"dependencies": [
|
||||||
"6"
|
"6"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": []
|
"subtasks": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "Create K8s API HTTP client and connection handling",
|
||||||
|
"description": "Implement a Kubernetes API client using node:http/https to communicate with the K8s API server, including authentication, TLS handling, and base request/response utilities.",
|
||||||
|
"dependencies": [],
|
||||||
|
"details": "Create src/mcpd/src/services/k8s/k8s-client.ts with: 1) K8sClientConfig interface supporting kubeconfig file parsing, in-cluster config detection, and direct API server URL/token config. 2) HTTP client wrapper using node:http/https that handles TLS certificates, bearer token auth, and API versioning. 3) Base request methods (get, post, delete, patch) with proper error handling and response parsing. 4) Support for watching resources with streaming responses. Reference the Docker container-manager.ts pattern for constructor options and ping() implementation.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Unit tests with mocked HTTP responses for successful API calls, auth failures, connection errors. Test kubeconfig parsing with sample config files. Test in-cluster config detection by mocking environment variables and service account token file.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "Implement K8s manifest generation for MCP servers",
|
||||||
|
"description": "Create manifest generator that converts ContainerSpec to Kubernetes Pod and Deployment YAML/JSON specifications with proper resource limits and security contexts.",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"details": "Create src/mcpd/src/services/k8s/manifest-generator.ts with: 1) generatePodSpec(spec: ContainerSpec, namespace: string) that creates a Pod manifest with container image, env vars, resource limits (CPU/memory from spec.nanoCpus and spec.memoryLimit), and labels including mcpctl.managed=true. 2) generateDeploymentSpec() for replicated deployments with selector labels. 3) generateServiceSpec() for exposing container ports. 4) Security context configuration (non-root user, read-only root filesystem, drop capabilities). 5) Map ContainerSpec fields to K8s equivalents (memoryLimit to resources.limits.memory, nanoCpus to resources.limits.cpu, etc.).",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Unit tests validating generated manifests match expected K8s spec structure. Test resource limit conversion (bytes to Ki/Mi/Gi, nanoCPUs to millicores). Test label propagation from ContainerSpec.labels. Validate manifests against K8s API schema if possible.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "Implement KubernetesOrchestrator class with McpOrchestrator interface",
|
||||||
|
"description": "Create the main KubernetesOrchestrator class that implements the McpOrchestrator interface using the K8s client and manifest generator.",
|
||||||
|
"dependencies": [
|
||||||
|
1,
|
||||||
|
2
|
||||||
|
],
|
||||||
|
"details": "Create src/mcpd/src/services/k8s/kubernetes-orchestrator.ts implementing McpOrchestrator interface: 1) Constructor accepting K8sClientConfig and default namespace. 2) ping() - call /api/v1 endpoint to verify cluster connectivity. 3) pullImage() - no-op for K8s (images pulled on pod schedule) or optionally create a pre-pull DaemonSet. 4) createContainer(spec) - generate Pod/Deployment manifest, POST to K8s API, wait for pod Ready condition, return ContainerInfo with pod name as containerId. 5) stopContainer(containerId) - scale deployment to 0 or delete pod. 6) removeContainer(containerId) - DELETE the pod/deployment resource. 7) inspectContainer(containerId) - GET pod status, map phase to ContainerInfo state (Running→running, Pending→starting, Failed→error, etc.). 8) getContainerLogs(containerId) - GET /api/v1/namespaces/{ns}/pods/{name}/log endpoint.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Integration tests with mocked K8s API responses for each method. Test createContainer returns valid ContainerInfo with mapped state. Test state mapping from K8s pod phases. Test log retrieval with tail and since parameters. Test error handling when pod not found or API errors.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "Add namespace and multi-namespace support",
|
||||||
|
"description": "Extend KubernetesOrchestrator to support configurable namespaces, namespace creation, and querying resources across namespaces.",
|
||||||
|
"dependencies": [
|
||||||
|
3
|
||||||
|
],
|
||||||
|
"details": "Enhance src/mcpd/src/services/k8s/kubernetes-orchestrator.ts with: 1) Add namespace parameter to ContainerSpec or use labels to specify target namespace. 2) ensureNamespace(name) method that creates namespace if not exists (POST /api/v1/namespaces). 3) listContainers(namespace?: string) method to list all mcpctl-managed pods in a namespace or all namespaces. 4) Add namespace to ContainerInfo response. 5) Support 'default' namespace fallback and configurable default namespace in constructor. 6) Add namespace label to generated manifests for filtering. 7) Validate namespace names (DNS-1123 label format).",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test namespace creation with mocked API. Test namespace validation for invalid names. Test listing pods across namespaces. Test ContainerInfo includes correct namespace. Test default namespace fallback behavior.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"title": "Add comprehensive tests and module exports",
|
||||||
|
"description": "Create unit tests with mocked K8s API responses, integration test utilities, and export the KubernetesOrchestrator from the services module.",
|
||||||
|
"dependencies": [
|
||||||
|
3,
|
||||||
|
4
|
||||||
|
],
|
||||||
|
"details": "1) Create src/mcpd/src/services/k8s/index.ts exporting KubernetesOrchestrator, K8sClientConfig, and helper types. 2) Update src/mcpd/src/services/index.ts to export k8s module. 3) Create src/mcpd/src/services/k8s/__tests__/kubernetes-orchestrator.test.ts with mocked HTTP responses using vitest's mock system. 4) Create mock-k8s-api.ts helper that simulates K8s API responses (pod list, pod status, logs, errors). 5) Test all McpOrchestrator interface methods with success and error cases. 6) Add tests for resource limit edge cases (0 memory, very high CPU). 7) Document usage examples in code comments showing how to switch from DockerContainerManager to KubernetesOrchestrator.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Ensure all tests pass with mocked responses. Verify test coverage for all public methods. Test error scenarios (404 pod not found, 403 forbidden, 500 server error). Optional: Add integration test script that runs against kind/minikube if available.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"updatedAt": "2026-02-21T05:30:53.921Z"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "18",
|
"id": "18",
|
||||||
@@ -649,8 +849,9 @@
|
|||||||
"9",
|
"9",
|
||||||
"10"
|
"10"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": []
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T05:19:02.525Z"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "19",
|
"id": "19",
|
||||||
@@ -658,7 +859,7 @@
|
|||||||
"description": "Merged into Task 3 subtasks",
|
"description": "Merged into Task 3 subtasks",
|
||||||
"details": null,
|
"details": null,
|
||||||
"testStrategy": null,
|
"testStrategy": null,
|
||||||
"priority": null,
|
"priority": "low",
|
||||||
"dependencies": [],
|
"dependencies": [],
|
||||||
"status": "cancelled",
|
"status": "cancelled",
|
||||||
"subtasks": [],
|
"subtasks": [],
|
||||||
@@ -670,7 +871,7 @@
|
|||||||
"description": "Merged into Task 5",
|
"description": "Merged into Task 5",
|
||||||
"details": null,
|
"details": null,
|
||||||
"testStrategy": null,
|
"testStrategy": null,
|
||||||
"priority": null,
|
"priority": "low",
|
||||||
"dependencies": [],
|
"dependencies": [],
|
||||||
"status": "cancelled",
|
"status": "cancelled",
|
||||||
"subtasks": [],
|
"subtasks": [],
|
||||||
@@ -682,7 +883,7 @@
|
|||||||
"description": "Merged into Task 14",
|
"description": "Merged into Task 14",
|
||||||
"details": null,
|
"details": null,
|
||||||
"testStrategy": null,
|
"testStrategy": null,
|
||||||
"priority": null,
|
"priority": "low",
|
||||||
"dependencies": [],
|
"dependencies": [],
|
||||||
"status": "cancelled",
|
"status": "cancelled",
|
||||||
"subtasks": [],
|
"subtasks": [],
|
||||||
@@ -699,8 +900,72 @@
|
|||||||
"6",
|
"6",
|
||||||
"14"
|
"14"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": []
|
"subtasks": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "Create MetricsCollector Service",
|
||||||
|
"description": "Implement a MetricsCollector service in src/mcpd/src/services/metrics-collector.ts that tracks instance health metrics, uptime, request counts, error rates, and resource usage data.",
|
||||||
|
"dependencies": [],
|
||||||
|
"details": "Create MetricsCollector class with methods: recordRequest(), recordError(), updateInstanceMetrics(), getMetrics(). Store metrics in-memory using Map<instanceId, InstanceMetrics>. Define InstanceMetrics interface with fields: instanceId, status, uptime, requestCount, errorCount, lastRequestAt, memoryUsage, cpuUsage. Inject IMcpInstanceRepository and McpOrchestrator dependencies to gather real-time instance status from containers. Export service from src/mcpd/src/services/index.ts.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Unit tests with mocked repository and orchestrator dependencies. Test metric recording, aggregation, and retrieval. Verify error rate calculations and uptime tracking accuracy.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "Implement Health Aggregation Service",
|
||||||
|
"description": "Create a HealthAggregator service that computes overall system health by aggregating health status across all MCP server instances.",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"details": "Add HealthAggregator class in src/mcpd/src/services/health-aggregator.ts. Methods: getOverview() returns SystemHealth with totalInstances, healthyCount, unhealthyCount, errorCount, and overallStatus (healthy/degraded/unhealthy). Use MetricsCollector to gather per-instance metrics. Include orchestrator.ping() check for runtime availability. Compute aggregate error rate and average uptime. Export from services/index.ts.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Unit tests with mocked MetricsCollector. Test aggregation logic for various instance states. Verify overall status determination rules (e.g., >50% unhealthy = degraded).",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "Create Health Monitoring REST Endpoints",
|
||||||
|
"description": "Implement REST endpoints for health monitoring: GET /api/v1/health/overview, GET /api/v1/health/instances/:id, and GET /api/v1/metrics in src/mcpd/src/routes/health-monitoring.ts.",
|
||||||
|
"dependencies": [
|
||||||
|
1,
|
||||||
|
2
|
||||||
|
],
|
||||||
|
"details": "Create registerHealthMonitoringRoutes(app, deps) function. GET /api/v1/health/overview returns SystemHealth from HealthAggregator.getOverview(). GET /api/v1/health/instances/:id returns InstanceMetrics for specific instance from MetricsCollector. GET /api/v1/metrics returns all metrics in Prometheus-compatible format or JSON. Add proper error handling for 404 when instance not found. Register routes in src/mcpd/src/routes/index.ts and wire up in server.ts.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Integration tests using Fastify inject(). Test all three endpoints with mocked services. Verify 200 responses with correct payload structure, 404 for missing instances.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "Add Request/Error Metrics Middleware",
|
||||||
|
"description": "Create middleware in src/mcpd/src/middleware/metrics.ts that intercepts requests to record metrics for request counts and error rates per instance.",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"details": "Implement Fastify preHandler hook that extracts instance ID from request params/query where applicable. Record request start time. Use onResponse hook to record completion and calculate latency. Use onError hook to record errors with MetricsCollector.recordError(). Track metrics per-route and per-instance. Register middleware in src/mcpd/src/middleware/index.ts. Apply to instance-related routes (/api/v1/instances/*) to track per-instance metrics.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Unit tests verifying hooks call MetricsCollector methods. Integration tests confirming request/error counts increment correctly after API calls.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"title": "Write Comprehensive Health Monitoring Tests",
|
||||||
|
"description": "Create test suite in src/mcpd/tests/health-monitoring.test.ts covering MetricsCollector, HealthAggregator, health monitoring routes, and metrics middleware.",
|
||||||
|
"dependencies": [
|
||||||
|
1,
|
||||||
|
2,
|
||||||
|
3,
|
||||||
|
4
|
||||||
|
],
|
||||||
|
"details": "Write tests for: MetricsCollector - test recordRequest(), recordError(), getMetrics(), concurrent access safety. HealthAggregator - test getOverview() with various instance states, edge cases (no instances, all unhealthy). Routes - test /api/v1/health/overview, /api/v1/health/instances/:id, /api/v1/metrics endpoints with mocked dependencies. Middleware - test request counting, error tracking, latency recording. Use vi.mock() for dependencies following existing test patterns in the codebase.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Self-referential - this subtask IS the test implementation. Verify all tests pass with `npm test`. Aim for >80% coverage on new health monitoring code.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"updatedAt": "2026-02-21T05:34:25.289Z"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "23",
|
"id": "23",
|
||||||
@@ -713,8 +978,71 @@
|
|||||||
"2",
|
"2",
|
||||||
"5"
|
"5"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": []
|
"subtasks": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "Implement BackupService for JSON export",
|
||||||
|
"description": "Create BackupService in src/mcpd/src/services/backup/ that exports servers, profiles, and projects from repositories to a structured JSON bundle.",
|
||||||
|
"dependencies": [],
|
||||||
|
"details": "Create BackupService class that uses IMcpServerRepository, IMcpProfileRepository, and IProjectRepository to fetch all data. Define a BackupBundle interface with metadata (version, timestamp, mcpctlVersion), servers array, profiles array, and projects array. Implement createBackup() method that aggregates all data into the bundle format. Add optional filtering by resource type (e.g., only servers, or only specific profiles). Export via services/index.ts following existing patterns.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Unit test BackupService with mocked repositories. Verify bundle structure includes all expected fields. Test filtering options. Test handling of empty repositories.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "Add secrets encryption using Node crypto",
|
||||||
|
"description": "Implement AES-256-GCM encryption for sensitive data in backup bundles using password-derived keys via scrypt.",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"details": "Create crypto utility module in src/mcpd/src/services/backup/crypto.ts using Node's built-in crypto module. Implement deriveKey() using scrypt with configurable salt length and key length. Implement encrypt() that creates IV, encrypts data with AES-256-GCM, and returns base64-encoded result with IV and auth tag prepended. Implement decrypt() that reverses the process. In BackupService, detect fields containing secrets (env vars with sensitive patterns like *_KEY, *_SECRET, *_TOKEN, PASSWORD) and encrypt them. Store encryption metadata (algorithm, salt) in bundle header.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test encryption/decryption round-trip with various data sizes. Verify wrong password fails decryption. Test key derivation produces consistent results with same inputs. Test detection of sensitive field patterns.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "Implement RestoreService for JSON import",
|
||||||
|
"description": "Create RestoreService that imports a backup bundle back into the system, handling decryption and conflict resolution.",
|
||||||
|
"dependencies": [
|
||||||
|
1,
|
||||||
|
2
|
||||||
|
],
|
||||||
|
"details": "Create RestoreService class in src/mcpd/src/services/backup/. Implement restore() method that parses JSON bundle, validates version compatibility, decrypts encrypted fields using provided password, and imports data using repositories. Support conflict resolution strategies: 'skip' (ignore existing), 'overwrite' (replace existing), 'fail' (abort on conflict). Implement validateBundle() for schema validation before import. Handle partial failures with transaction-like rollback or detailed error reporting.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test restore with valid bundle creates expected resources. Test conflict resolution modes (skip, overwrite, fail). Test encrypted bundle restore with correct/incorrect passwords. Test invalid bundle rejection.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "Add REST endpoints for backup and restore",
|
||||||
|
"description": "Create REST API routes in src/mcpd/src/routes/ for triggering backup creation and restore operations.",
|
||||||
|
"dependencies": [
|
||||||
|
1,
|
||||||
|
2,
|
||||||
|
3
|
||||||
|
],
|
||||||
|
"details": "Create backup.ts routes file with: POST /api/v1/backup (create backup, optional password for encryption, returns JSON bundle), POST /api/v1/restore (accepts JSON bundle in body, password if encrypted, conflict strategy option, returns import summary). Register routes in routes/index.ts. Define BackupDeps interface following existing patterns. Add appropriate error handling for invalid bundles, decryption failures, and conflict errors. Include validation schemas for request bodies.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Integration test backup endpoint returns valid JSON bundle. Test restore endpoint with valid/invalid bundles. Test encrypted backup/restore round-trip via API. Test error responses for various failure scenarios.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"title": "Add CLI commands for backup and restore",
|
||||||
|
"description": "Implement CLI commands in src/cli/src/commands/ for backup export to file and restore from file.",
|
||||||
|
"dependencies": [
|
||||||
|
4
|
||||||
|
],
|
||||||
|
"details": "Create backup.ts commands file with: 'mcpctl backup' command with options --output/-o (file path), --encrypt (prompt for password), --resources (filter: servers,profiles,projects). Create 'mcpctl restore' command with options --input/-i (file path), --password (or prompt if encrypted), --conflict (skip|overwrite|fail). Commands should call the daemon API endpoints. Add progress output and summary of backed up/restored resources. Register commands in cli/src/index.ts following existing createXxxCommand pattern.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test backup command creates valid file. Test restore command from backup file. Test encryption password prompting. Test --resources filtering. Test various conflict resolution modes via CLI.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"updatedAt": "2026-02-21T05:40:51.787Z"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "24",
|
"id": "24",
|
||||||
@@ -726,15 +1054,367 @@
|
|||||||
"dependencies": [
|
"dependencies": [
|
||||||
"1"
|
"1"
|
||||||
],
|
],
|
||||||
"status": "pending",
|
"status": "done",
|
||||||
"subtasks": []
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T05:12:31.235Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "25",
|
||||||
|
"title": "Rename local-proxy to mcplocal",
|
||||||
|
"description": "Rename the src/local-proxy directory to src/mcplocal and update all package references, imports, and build configurations throughout the monorepo.",
|
||||||
|
"details": "1. Rename directory: `mv src/local-proxy src/mcplocal`\n2. Update package.json name from `@mcpctl/local-proxy` to `@mcpctl/mcplocal`\n3. Update pnpm-workspace.yaml if needed\n4. Update all imports in other packages that reference local-proxy:\n - Search for `@mcpctl/local-proxy` and replace with `@mcpctl/mcplocal`\n - Check tsconfig references and path mappings\n5. Update any scripts in package.json root that reference local-proxy\n6. Update docker-compose files in deploy/ if they reference local-proxy\n7. Update documentation and README references\n8. Run `pnpm install` to regenerate lockfile with new package name\n9. Verify TypeScript compilation succeeds: `pnpm build`\n10. Run existing tests to ensure nothing broke: `pnpm test`",
|
||||||
|
"testStrategy": "1. Verify directory rename completed: `ls src/mcplocal`\n2. Verify package.json has correct name\n3. Run `pnpm install` - should complete without errors\n4. Run `pnpm build` - all packages should compile\n5. Run `pnpm test` - all existing tests should pass\n6. Grep codebase for 'local-proxy' - should find no stale references except git history",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [],
|
||||||
|
"status": "done",
|
||||||
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T18:04:17.018Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "26",
|
||||||
|
"title": "Add HTTP REST server to mcplocal",
|
||||||
|
"description": "Add a Fastify HTTP server to mcplocal that runs alongside the existing stdio server, providing REST endpoints for mcpctl management commands.",
|
||||||
|
"details": "1. Add Fastify dependency to mcplocal package.json: `@fastify/cors`, `fastify`\n2. Create `src/mcplocal/src/http/server.ts` with Fastify app setup:\n ```typescript\n import Fastify from 'fastify';\n import cors from '@fastify/cors';\n \n export async function createHttpServer(config: HttpServerConfig) {\n const app = Fastify({ logger: true });\n await app.register(cors, { origin: true });\n // Register routes\n return app;\n }\n ```\n3. Create `src/mcplocal/src/http/routes/` directory structure\n4. Create health check endpoint: `GET /health`\n5. Create config types in `src/mcplocal/src/config.ts`:\n - `httpPort`: number (default 3200)\n - `httpHost`: string (default '127.0.0.1')\n - `mcpdUrl`: string (default 'http://localhost:3100')\n6. Update mcplocal entry point to start both servers:\n - stdio server for Claude MCP protocol\n - HTTP server for mcpctl REST API\n7. Add graceful shutdown handling for both servers",
|
||||||
|
"testStrategy": "1. Unit test: HTTP server starts on configured port\n2. Unit test: Health endpoint returns 200 OK\n3. Integration test: Both stdio and HTTP servers can run simultaneously\n4. Test graceful shutdown stops both servers cleanly\n5. Test CORS headers are present on responses\n6. Manual test: curl http://localhost:3200/health",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
"25"
|
||||||
|
],
|
||||||
|
"status": "done",
|
||||||
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T18:09:26.322Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "27",
|
||||||
|
"title": "Implement mcplocal management proxy routes",
|
||||||
|
"description": "Add REST endpoints to mcplocal that mirror mcpd's API and proxy management requests to mcpd without LLM processing. All requests must include proper authentication to mcpd using a Bearer token read from mcplocal config.",
|
||||||
|
"status": "done",
|
||||||
|
"dependencies": [
|
||||||
|
"26"
|
||||||
|
],
|
||||||
|
"priority": "high",
|
||||||
|
"details": "1. Create HTTP client for mcpd communication with auth: `src/local-proxy/src/http/mcpd-client.ts`\n ```typescript\n export class McpdClient {\n private token: string;\n \n constructor(private baseUrl: string, token: string) {\n this.token = token;\n }\n \n private getHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.token}`\n };\n }\n \n async get<T>(path: string): Promise<T> {\n const response = await fetch(`${this.baseUrl}${path}`, {\n method: 'GET',\n headers: this.getHeaders()\n });\n await this.handleAuthError(response);\n return response.json();\n }\n \n async post<T>(path: string, body: unknown): Promise<T> {\n const response = await fetch(`${this.baseUrl}${path}`, {\n method: 'POST',\n headers: this.getHeaders(),\n body: JSON.stringify(body)\n });\n await this.handleAuthError(response);\n return response.json();\n }\n \n async put<T>(path: string, body: unknown): Promise<T> {\n const response = await fetch(`${this.baseUrl}${path}`, {\n method: 'PUT',\n headers: this.getHeaders(),\n body: JSON.stringify(body)\n });\n await this.handleAuthError(response);\n return response.json();\n }\n \n async delete<T>(path: string): Promise<T> {\n const response = await fetch(`${this.baseUrl}${path}`, {\n method: 'DELETE',\n headers: this.getHeaders()\n });\n await this.handleAuthError(response);\n return response.json();\n }\n \n private async handleAuthError(response: Response): Promise<void> {\n if (response.status === 401) {\n throw new AuthenticationError('Invalid or expired token. Please check mcplocal config.');\n }\n }\n }\n \n export class AuthenticationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AuthenticationError';\n }\n }\n ```\n2. Add token to mcplocal config type (extend ProxyConfig or similar):\n ```typescript\n export interface McpdAuthConfig {\n /** Bearer token for mcpd API authentication */\n mcpdToken: string;\n }\n ```\n3. Create proxy routes in `src/local-proxy/src/http/routes/`:\n - `servers.ts`: GET/POST /api/v1/servers, GET/PUT/DELETE /api/v1/servers/:id\n - `profiles.ts`: GET/POST /api/v1/profiles, GET/PUT/DELETE /api/v1/profiles/:id\n - `instances.ts`: GET/POST /api/v1/instances, GET/POST/DELETE /api/v1/instances/:id, etc.\n - `projects.ts`: GET/POST /api/v1/projects, etc.\n - `audit.ts`: GET /api/v1/audit-logs\n - `backup.ts`: POST /api/v1/backup, POST /api/v1/restore\n4. Each route handler forwards to mcpd with auth:\n ```typescript\n app.get('/api/v1/servers', async (req, reply) => {\n try {\n const result = await mcpdClient.get('/api/v1/servers');\n return result;\n } catch (error) {\n if (error instanceof AuthenticationError) {\n return reply.status(401).send({ error: error.message });\n }\n throw error;\n }\n });\n ```\n5. Add comprehensive error handling:\n - If mcpd is unreachable, return 503 Service Unavailable\n - If mcpd returns 401, return 401 with clear message about token configuration\n - Forward other HTTP errors from mcpd with appropriate status codes\n6. Add request/response logging for debugging",
|
||||||
|
"testStrategy": "1. Unit test: McpdClient attaches Authorization header to all request methods (GET, POST, PUT, DELETE)\n2. Unit test: McpdClient throws AuthenticationError on 401 response from mcpd\n3. Unit test: Each proxy route forwards requests correctly with auth headers\n4. Unit test: Error handling when mcpd is unreachable (503 response)\n5. Unit test: Error handling when mcpd returns 401 (clear error message returned)\n6. Integration test: Full request flow mcpctl -> mcplocal -> mcpd with valid token\n7. Integration test: Full request flow with invalid token returns 401\n8. Test query parameters are forwarded correctly\n9. Test request body is forwarded correctly for POST/PUT\n10. Test path parameters (:id) are passed through correctly\n11. Mock mcpd responses and verify mcplocal returns them unchanged\n12. Test token is read correctly from mcplocal config",
|
||||||
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T18:34:20.942Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "28",
|
||||||
|
"title": "Add MCP proxy endpoint to mcpd",
|
||||||
|
"description": "Create a new endpoint in mcpd at /api/v1/mcp/proxy that accepts MCP tool call requests and executes them on managed MCP server instances. Also add authentication endpoints (login/logout) that mcpctl will use to authenticate users.",
|
||||||
|
"status": "done",
|
||||||
|
"dependencies": [],
|
||||||
|
"priority": "high",
|
||||||
|
"details": "## MCP Proxy Endpoint\n\n1. Create new route file: `src/mcpd/src/routes/mcp-proxy.ts`\n2. Define request schema:\n ```typescript\n interface McpProxyRequest {\n serverId: string; // or instanceId\n method: string; // e.g., 'tools/call', 'resources/read'\n params: Record<string, unknown>;\n }\n ```\n3. Create McpProxyService in `src/mcpd/src/services/mcp-proxy-service.ts`:\n - Look up instance by serverId (auto-start if profile allows)\n - Connect to the container via stdio or HTTP (depending on transport type)\n - Execute the MCP JSON-RPC call\n - Return the result\n4. Handle MCP JSON-RPC protocol:\n ```typescript\n async executeCall(instanceId: string, method: string, params: unknown) {\n const instance = await this.instanceService.getInstance(instanceId);\n const connection = await this.getOrCreateConnection(instance);\n const result = await connection.call(method, params);\n return result;\n }\n ```\n5. Connection pooling: maintain persistent connections to running instances\n6. Add route: `POST /api/v1/mcp/proxy` (must be behind auth middleware)\n7. Add audit logging for all MCP proxy calls - include authenticated userId from request.userId\n8. Handle errors: instance not found, instance not running, MCP call failed\n\n## Authentication Endpoints\n\n9. Create auth routes file: `src/mcpd/src/routes/auth.ts`\n10. Implement `POST /api/v1/auth/login`:\n - Request body: `{ username: string, password: string }`\n - Validate credentials against User table (use bcrypt for password comparison)\n - Create new Session record with token (use crypto.randomUUID or similar)\n - Response: `{ token: string, expiresAt: string }`\n11. Implement `POST /api/v1/auth/logout`:\n - Requires Bearer token in Authorization header\n - Delete/invalidate the Session record\n - Response: `{ success: true }`\n\n## Auth Integration Notes\n\n- Existing auth middleware in `src/mcpd/src/middleware/auth.ts` validates Bearer tokens against Session table\n- It sets `request.userId` on successful authentication\n- MCP proxy endpoint MUST use this auth middleware\n- Auth endpoints (login) should NOT require auth middleware\n- Logout endpoint SHOULD require auth middleware to validate the session being invalidated",
|
||||||
|
"testStrategy": "1. Unit test: Proxy service looks up correct instance\n2. Unit test: JSON-RPC call is formatted correctly\n3. Integration test: Full flow with a mock MCP server container\n4. Test error handling: non-existent server returns 404\n5. Test error handling: stopped instance returns appropriate error\n6. Test audit log entries include authenticated userId\n7. Test connection reuse for multiple calls to same instance\n8. Test login endpoint: valid credentials return session token\n9. Test login endpoint: invalid credentials return 401\n10. Test logout endpoint: valid session is invalidated\n11. Test logout endpoint: invalid/missing token returns 401\n12. Test MCP proxy endpoint without auth token returns 401\n13. Test MCP proxy endpoint with expired token returns 401\n14. Test MCP proxy endpoint with valid token succeeds and logs userId in audit",
|
||||||
|
"subtasks": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "Create auth routes with login/logout endpoints",
|
||||||
|
"description": "Create src/mcpd/src/routes/auth.ts with POST /api/v1/auth/login and POST /api/v1/auth/logout endpoints for mcpctl authentication.",
|
||||||
|
"dependencies": [],
|
||||||
|
"details": "Implement login endpoint: validate username/password against User table using bcrypt, create Session record with generated token and expiry. Implement logout endpoint: require auth middleware, delete/invalidate Session record. Login does NOT require auth, logout DOES require auth. Export registerAuthRoutes function and update routes/index.ts.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test login with valid/invalid credentials. Test logout invalidates session. Test logout requires valid auth token. Test session token format and expiry.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "Create MCP proxy route file with auth middleware",
|
||||||
|
"description": "Create src/mcpd/src/routes/mcp-proxy.ts with POST /api/v1/mcp/proxy endpoint protected by auth middleware.",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"details": "Define McpProxyRequest interface (serverId, method, params). Register route handler that extracts userId from request.userId (set by auth middleware). Apply auth middleware using preHandler hook. Validate request body schema.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test endpoint returns 401 without auth token. Test endpoint returns 401 with invalid/expired token. Test valid auth token allows request through.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "Create McpProxyService for instance lookup and connection",
|
||||||
|
"description": "Create src/mcpd/src/services/mcp-proxy-service.ts to handle instance lookup, connection management, and MCP call execution.",
|
||||||
|
"dependencies": [],
|
||||||
|
"details": "Implement getInstance to look up by serverId, auto-start if profile allows. Implement getOrCreateConnection for connection pooling. Handle both stdio and HTTP transports. Implement executeCall method that formats JSON-RPC call and returns result.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Unit test instance lookup. Unit test connection pooling reuses connections. Test auto-start behavior. Test both transport types.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "Implement MCP JSON-RPC call execution",
|
||||||
|
"description": "Implement the core JSON-RPC call logic in McpProxyService to execute tool calls on MCP server instances.",
|
||||||
|
"dependencies": [
|
||||||
|
3
|
||||||
|
],
|
||||||
|
"details": "Format JSON-RPC 2.0 request with method and params. Send request over established connection (stdio/HTTP). Parse JSON-RPC response and handle errors. Return result or throw appropriate error for failed calls.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Unit test JSON-RPC request formatting. Test successful call returns result. Test JSON-RPC error responses are handled. Integration test with mock MCP server.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"title": "Add audit logging with userId for MCP proxy calls",
|
||||||
|
"description": "Ensure all MCP proxy calls are logged to audit log including the authenticated userId from the session.",
|
||||||
|
"dependencies": [
|
||||||
|
2,
|
||||||
|
4
|
||||||
|
],
|
||||||
|
"details": "Use existing audit middleware/service. Include userId from request.userId in audit log entry. Log serverId, method, and outcome (success/failure). Log any errors that occur during MCP call execution.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test audit log entries contain userId. Test audit log entries contain serverId and method. Test failed calls are logged with error details.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 6,
|
||||||
|
"title": "Integrate auth and proxy routes into server.ts",
|
||||||
|
"description": "Register the new auth and mcp-proxy routes in the Fastify server with proper auth middleware wiring.",
|
||||||
|
"dependencies": [
|
||||||
|
1,
|
||||||
|
2,
|
||||||
|
5
|
||||||
|
],
|
||||||
|
"details": "Update server.ts to register auth routes (no auth required for login). Register mcp-proxy routes with auth middleware. Ensure auth middleware is wired with findSession dependency from Prisma. Update routes/index.ts exports.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Integration test full login -> proxy call flow. Test auth middleware correctly protects proxy endpoint. Test health endpoints remain unauthenticated.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"updatedAt": "2026-02-21T18:09:26.327Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "29",
|
||||||
|
"title": "Implement LLM pre-processing pipeline in mcplocal",
|
||||||
|
"description": "Create the core LLM pre-processing pipeline that intercepts MCP tool calls, uses a local LLM to optimize requests before sending to mcpd, and filters responses before returning to Claude.",
|
||||||
|
"details": "1. Create `src/mcplocal/src/llm/processor.ts` - the core pipeline:\n ```typescript\n export class LlmProcessor {\n constructor(\n private providerRegistry: ProviderRegistry,\n private config: LlmProcessorConfig\n ) {}\n \n async preprocessRequest(toolName: string, params: unknown): Promise<ProcessedRequest> {\n // Use LLM to interpret and optimize the request\n const prompt = this.buildRequestPrompt(toolName, params);\n const result = await this.providerRegistry.getActiveProvider().complete({\n systemPrompt: REQUEST_OPTIMIZATION_SYSTEM_PROMPT,\n userPrompt: prompt\n });\n return this.parseOptimizedRequest(result);\n }\n \n async filterResponse(toolName: string, originalRequest: unknown, rawResponse: unknown): Promise<FilteredResponse> {\n // Use LLM to filter/summarize the response\n const prompt = this.buildFilterPrompt(toolName, originalRequest, rawResponse);\n const result = await this.providerRegistry.getActiveProvider().complete({\n systemPrompt: RESPONSE_FILTER_SYSTEM_PROMPT,\n userPrompt: prompt\n });\n return this.parseFilteredResponse(result);\n }\n }\n ```\n2. Create system prompts in `src/mcplocal/src/llm/prompts.ts`:\n - REQUEST_OPTIMIZATION_SYSTEM_PROMPT: instruct LLM to generate optimal queries\n - RESPONSE_FILTER_SYSTEM_PROMPT: instruct LLM to extract relevant information\n3. Integrate into router.ts - wrap tools/call handler:\n ```typescript\n async handleToolsCall(request: JsonRpcRequest) {\n if (this.shouldPreprocess(request.params.name)) {\n const processed = await this.llmProcessor.preprocessRequest(...);\n // Call mcpd with processed request\n const rawResponse = await this.callMcpd(processed);\n const filtered = await this.llmProcessor.filterResponse(...);\n return filtered;\n }\n return this.callMcpd(request.params);\n }\n ```\n4. Add configuration options:\n - `enablePreprocessing`: boolean\n - `preprocessingExclude`: string[] (tool names to skip)\n - `preferredProvider`: string (ollama, gemini, deepseek, etc.)\n5. Add bypass logic for simple operations (list, create, delete)",
|
||||||
|
"testStrategy": "1. Unit test: Request preprocessing generates optimized queries\n2. Unit test: Response filtering reduces data volume\n3. Unit test: Bypass logic works for excluded tools\n4. Integration test: Full pipeline with mock LLM provider\n5. Test error handling: LLM failure falls back to unfiltered pass-through\n6. Test configuration options are respected\n7. Measure: response size reduction percentage",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
"25",
|
||||||
|
"27",
|
||||||
|
"28"
|
||||||
|
],
|
||||||
|
"status": "done",
|
||||||
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T18:41:26.539Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "30",
|
||||||
|
"title": "Add Gemini CLI LLM provider",
|
||||||
|
"description": "Implement a new LLM provider that uses the Gemini CLI binary for local, free LLM inference as the preferred provider for pre-processing.",
|
||||||
|
"details": "1. Create `src/mcplocal/src/providers/gemini-cli.ts`:\n ```typescript\n import { spawn } from 'child_process';\n \n export class GeminiCliProvider implements LlmProvider {\n readonly name = 'gemini-cli';\n private binaryPath: string;\n \n constructor(config: GeminiCliConfig) {\n this.binaryPath = config.binaryPath || 'gemini';\n }\n \n async isAvailable(): Promise<boolean> {\n // Check if gemini binary exists and is executable\n try {\n await this.runCommand(['--version']);\n return true;\n } catch {\n return false;\n }\n }\n \n async complete(options: CompletionOptions): Promise<CompletionResult> {\n const input = this.formatPrompt(options);\n const output = await this.runCommand(['--prompt', input]);\n return { content: output, model: 'gemini-cli' };\n }\n \n private async runCommand(args: string[]): Promise<string> {\n // Spawn gemini CLI process and capture output\n }\n }\n ```\n2. Research actual Gemini CLI interface and adjust implementation\n3. Add to provider registry with high priority (prefer over API providers)\n4. Add configuration: `geminiCliBinaryPath`\n5. Handle timeout for slow inference\n6. Add fallback to next provider if Gemini CLI fails",
|
||||||
|
"testStrategy": "1. Unit test: Provider correctly detects CLI availability\n2. Unit test: Prompt formatting is correct\n3. Unit test: Output parsing handles various formats\n4. Integration test: Full completion with actual Gemini CLI (if available)\n5. Test timeout handling for slow responses\n6. Test fallback when CLI is not installed",
|
||||||
|
"priority": "medium",
|
||||||
|
"dependencies": [
|
||||||
|
"25"
|
||||||
|
],
|
||||||
|
"status": "done",
|
||||||
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T18:34:20.968Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "31",
|
||||||
|
"title": "Add DeepSeek API LLM provider",
|
||||||
|
"description": "Implement DeepSeek API provider as a cheap cloud-based fallback when local LLMs are unavailable.",
|
||||||
|
"details": "1. Create `src/mcplocal/src/providers/deepseek.ts`:\n ```typescript\n export class DeepSeekProvider implements LlmProvider {\n readonly name = 'deepseek';\n private apiKey: string;\n private baseUrl = 'https://api.deepseek.com/v1';\n \n constructor(config: DeepSeekConfig) {\n this.apiKey = config.apiKey || process.env.DEEPSEEK_API_KEY;\n }\n \n async isAvailable(): Promise<boolean> {\n return !!this.apiKey;\n }\n \n async complete(options: CompletionOptions): Promise<CompletionResult> {\n // DeepSeek uses OpenAI-compatible API\n const response = await fetch(`${this.baseUrl}/chat/completions`, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n model: 'deepseek-chat',\n messages: [{ role: 'user', content: options.userPrompt }]\n })\n });\n // Parse and return\n }\n }\n ```\n2. Add DEEPSEEK_API_KEY to configuration\n3. Register in provider registry with medium priority\n4. Support both deepseek-chat and deepseek-coder models\n5. Add rate limiting handling",
|
||||||
|
"testStrategy": "1. Unit test: Provider correctly checks API key availability\n2. Unit test: Request formatting matches DeepSeek API spec\n3. Unit test: Response parsing handles all fields\n4. Integration test: Full completion with actual API (with valid key)\n5. Test error handling for rate limits\n6. Test error handling for invalid API key",
|
||||||
|
"priority": "medium",
|
||||||
|
"dependencies": [
|
||||||
|
"25"
|
||||||
|
],
|
||||||
|
"status": "done",
|
||||||
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T18:34:20.974Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "32",
|
||||||
|
"title": "Implement smart context optimization",
|
||||||
|
"description": "Add token counting and decision logic to intelligently skip LLM filtering when responses are small enough, and cache filtering decisions for repeated queries.",
|
||||||
|
"details": "1. Create `src/mcplocal/src/llm/token-counter.ts`:\n ```typescript\n export function estimateTokens(text: string): number {\n // Simple estimation: ~4 chars per token for English\n // More accurate: use tiktoken or similar library\n return Math.ceil(text.length / 4);\n }\n ```\n2. Create `src/mcplocal/src/llm/filter-cache.ts`:\n ```typescript\n export class FilterCache {\n private cache: LRUCache<string, FilterDecision>;\n \n shouldFilter(toolName: string, params: unknown, responseSize: number): boolean {\n const key = this.computeKey(toolName, params);\n const cached = this.cache.get(key);\n if (cached) return cached.shouldFilter;\n // No cache hit - use default threshold logic\n return responseSize > this.tokenThreshold;\n }\n \n recordDecision(toolName: string, params: unknown, decision: FilterDecision): void {\n const key = this.computeKey(toolName, params);\n this.cache.set(key, decision);\n }\n }\n ```\n3. Add configuration options:\n - `tokenThreshold`: number (default 1000 tokens)\n - `filterCacheSize`: number (default 1000 entries)\n - `filterCacheTtl`: number (default 3600 seconds)\n4. Integrate into LlmProcessor:\n ```typescript\n async filterResponse(...) {\n const tokens = estimateTokens(JSON.stringify(rawResponse));\n if (tokens < this.config.tokenThreshold) {\n // Not worth filtering - return as-is\n return { filtered: false, response: rawResponse };\n }\n // Proceed with LLM filtering\n }\n ```\n5. Add metrics tracking:\n - Total tokens processed\n - Tokens saved by filtering\n - Filter cache hit rate\n - Average latency added by filtering",
|
||||||
|
"testStrategy": "1. Unit test: Token estimation is reasonably accurate\n2. Unit test: Cache correctly stores and retrieves decisions\n3. Unit test: Threshold logic skips filtering for small responses\n4. Unit test: Cache TTL expiration works correctly\n5. Integration test: Metrics are recorded accurately\n6. Performance test: Cache improves latency for repeated queries",
|
||||||
|
"priority": "medium",
|
||||||
|
"dependencies": [
|
||||||
|
"29"
|
||||||
|
],
|
||||||
|
"status": "done",
|
||||||
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T18:47:07.709Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "33",
|
||||||
|
"title": "Update mcpctl to use mcplocal as daemon",
|
||||||
|
"description": "Modify mcpctl CLI to connect to mcplocal instead of mcpd directly, update configuration options, add dual connectivity status checking, and implement authentication commands (login/logout) with secure credential storage.",
|
||||||
|
"status": "done",
|
||||||
|
"dependencies": [
|
||||||
|
"27"
|
||||||
|
],
|
||||||
|
"priority": "high",
|
||||||
|
"details": "1. Update `src/cli/src/config/schema.ts`:\n ```typescript\n export interface McpctlConfig {\n mcplocalUrl: string; // NEW: default 'http://localhost:3200'\n mcpdUrl: string; // Keep for reference/direct access if needed\n // ... other fields\n }\n ```\n2. Update `src/cli/src/config/defaults.ts`:\n - Change default daemonUrl to http://localhost:3200 (mcplocal)\n3. Update `src/cli/src/api-client.ts`:\n - Default baseUrl now points to mcplocal\n4. Add new config commands in `src/cli/src/commands/config.ts`:\n ```typescript\n .command('set-mcplocal-url <url>')\n .command('set-mcpd-url <url>')\n .command('get-mcplocal-url')\n .command('get-mcpd-url')\n ```\n5. Update `src/cli/src/commands/status.ts` to show both connections and auth status:\n ```\n $ mcpctl status\n mcplocal: connected (localhost:3200)\n mcpd: connected (nas.local:3100) via mcplocal\n Auth: logged in as user@example.com\n LLM Provider: ollama (llama3.2)\n Token savings: 45% (last 24h)\n ```\n6. Update CLI --daemon-url flag to point to mcplocal\n7. Add --direct flag to bypass mcplocal and talk to mcpd directly (for debugging)\n8. Create `src/cli/src/commands/auth.ts` with login/logout commands:\n - `mcpctl login`: Prompt for mcpd URL (if not configured) and credentials\n - Call POST /api/v1/auth/login with { email, password }\n - Store session token in ~/.mcpctl/credentials with 0600 permissions\n - `mcpctl logout`: Invalidate session and delete stored token\n9. Create `src/cli/src/auth/credentials.ts` for secure token storage:\n - Use fs.chmod to set 0600 permissions on credentials file\n - Token format: { token: string, mcpdUrl: string, user: string, expiresAt?: string }\n10. Update api-client.ts to include stored token in requests to mcplocal\n - mcplocal passes this token to mcpd for authentication",
|
||||||
|
"testStrategy": "1. Unit test: Default config points to mcplocal URL\n2. Unit test: Config commands update correct fields\n3. Integration test: CLI commands work through mcplocal proxy\n4. Test status command shows both mcplocal and mcpd status\n5. Test --direct flag bypasses mcplocal\n6. Test backward compatibility with existing config files\n7. Unit test: login command stores token with correct permissions (0600)\n8. Unit test: logout command removes credentials file\n9. Integration test: login flow with POST /api/v1/auth/login\n10. Test status command shows auth status (logged in as user)\n11. Test token is passed to mcplocal in API requests\n12. Test invalid credentials return appropriate error message\n13. Test expired token handling",
|
||||||
|
"subtasks": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "Update config schema for mcplocal and mcpd URLs",
|
||||||
|
"description": "Modify McpctlConfigSchema in src/cli/src/config/schema.ts to include separate mcplocalUrl and mcpdUrl fields with appropriate defaults.",
|
||||||
|
"dependencies": [],
|
||||||
|
"details": "Update the Zod schema to add mcplocalUrl (default: http://localhost:3200) and mcpdUrl (default: http://localhost:3100). Update DEFAULT_CONFIG and ensure backward compatibility with existing daemonUrl field by mapping it to mcplocalUrl.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Unit test schema validation for new URL fields. Test default values are correct. Test backward compatibility mapping.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "Create auth credentials storage module",
|
||||||
|
"description": "Create src/cli/src/auth/credentials.ts to handle secure storage and retrieval of session tokens in ~/.mcpctl/credentials.",
|
||||||
|
"dependencies": [],
|
||||||
|
"details": "Implement saveCredentials(token, mcpdUrl, user), loadCredentials(), and deleteCredentials() functions. Use fs.chmod to set 0600 permissions. Store JSON format: { token, mcpdUrl, user, expiresAt }. Handle file not found gracefully in loadCredentials.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Unit test credentials are saved with 0600 permissions. Test load returns null when file doesn't exist. Test delete removes the file.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "Implement login command",
|
||||||
|
"description": "Create src/cli/src/commands/auth.ts with mcpctl login command that prompts for mcpd URL and credentials, calls POST /api/v1/auth/login, and stores the session token.",
|
||||||
|
"dependencies": [
|
||||||
|
2
|
||||||
|
],
|
||||||
|
"details": "Use inquirer or prompts library for interactive credential input (email, password). If mcpdUrl not configured, prompt for it. Call POST /api/v1/auth/login with credentials. On success, save token using credentials module. Display 'Logged in as {user}' on success. Handle errors (invalid credentials, network errors) with clear messages.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test prompts collect correct input. Test successful login stores credentials. Test failed login shows error without storing token.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "Implement logout command",
|
||||||
|
"description": "Add mcpctl logout command to auth.ts that invalidates the session and removes stored credentials.",
|
||||||
|
"dependencies": [
|
||||||
|
2
|
||||||
|
],
|
||||||
|
"details": "Load stored credentials, optionally call a logout endpoint on mcpd to invalidate server-side session, then delete the local credentials file. Display 'Logged out successfully' or 'Not logged in' as appropriate.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test logout removes credentials file. Test logout when not logged in shows appropriate message.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"title": "Update api-client to include auth token",
|
||||||
|
"description": "Modify src/cli/src/api-client.ts to load and include stored session token in Authorization header for requests to mcplocal.",
|
||||||
|
"dependencies": [
|
||||||
|
2
|
||||||
|
],
|
||||||
|
"details": "Import loadCredentials from auth module. Add Authorization: Bearer {token} header to requests when credentials exist. Handle expired token by returning appropriate error suggesting re-login.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test requests include Authorization header when logged in. Test requests work without token when not logged in.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 6,
|
||||||
|
"title": "Update status command to show auth status",
|
||||||
|
"description": "Modify src/cli/src/commands/status.ts to display authentication status (logged in as user X or not logged in) along with mcplocal and mcpd connectivity.",
|
||||||
|
"dependencies": [
|
||||||
|
2,
|
||||||
|
5
|
||||||
|
],
|
||||||
|
"details": "Load credentials and display auth status line: 'Auth: logged in as {user}' or 'Auth: not logged in'. Update status output format to show mcplocal and mcpd status separately with the auth info.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test status shows 'logged in as user' when credentials exist. Test status shows 'not logged in' when no credentials.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 7,
|
||||||
|
"title": "Add config commands for mcplocal and mcpd URLs",
|
||||||
|
"description": "Add set-mcplocal-url, set-mcpd-url, get-mcplocal-url, and get-mcpd-url commands to src/cli/src/commands/config.ts.",
|
||||||
|
"dependencies": [
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"details": "Add four new subcommands to the config command for setting and getting the mcplocal and mcpd URLs independently. Update the generic 'set' command to handle these new schema fields.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test each command correctly reads/writes the appropriate config field.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 8,
|
||||||
|
"title": "Add --direct flag for mcpd bypass",
|
||||||
|
"description": "Add --direct flag to CLI commands that bypasses mcplocal and connects directly to mcpd for debugging purposes.",
|
||||||
|
"dependencies": [
|
||||||
|
1,
|
||||||
|
5
|
||||||
|
],
|
||||||
|
"details": "Add global --direct option to the main CLI. When set, api-client uses mcpdUrl instead of mcplocalUrl. Useful for debugging connectivity issues between mcplocal and mcpd.",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test --direct flag causes requests to use mcpdUrl. Test normal operation uses mcplocalUrl.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 9,
|
||||||
|
"title": "Register auth commands in CLI entry point",
|
||||||
|
"description": "Import and register the login and logout commands in src/cli/src/index.ts.",
|
||||||
|
"dependencies": [
|
||||||
|
3,
|
||||||
|
4
|
||||||
|
],
|
||||||
|
"details": "Import createAuthCommand from commands/auth.ts and add it to the main program with program.addCommand(createAuthCommand()).",
|
||||||
|
"status": "pending",
|
||||||
|
"testStrategy": "Test mcpctl login and mcpctl logout are available as commands.",
|
||||||
|
"parentId": "undefined"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"updatedAt": "2026-02-21T18:39:11.345Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "34",
|
||||||
|
"title": "Connect mcplocal MCP router to mcpd proxy endpoint",
|
||||||
|
"description": "Update mcplocal's MCP router to forward tool calls to mcpd's new /api/v1/mcp/proxy endpoint instead of connecting to MCP servers directly.",
|
||||||
|
"details": "1. Update `src/mcplocal/src/router.ts` to use mcpd proxy:\n ```typescript\n class Router {\n private mcpdClient: McpdClient;\n \n async handleToolsCall(request: JsonRpcRequest) {\n const { name, arguments: args } = request.params;\n const [serverName, toolName] = name.split('/');\n \n // Pre-process with LLM if enabled\n const processedArgs = this.config.enablePreprocessing\n ? await this.llmProcessor.preprocessRequest(toolName, args)\n : args;\n \n // Call mcpd proxy endpoint\n const result = await this.mcpdClient.post('/api/v1/mcp/proxy', {\n serverId: serverName,\n method: 'tools/call',\n params: { name: toolName, arguments: processedArgs }\n });\n \n // Post-process response with LLM if enabled\n return this.config.enablePreprocessing\n ? await this.llmProcessor.filterResponse(toolName, args, result)\n : result;\n }\n }\n ```\n2. Update upstream configuration:\n - Remove direct upstream connections for managed servers\n - Keep option for local/unmanaged upstreams\n3. Add server discovery from mcpd:\n ```typescript\n async refreshServerList() {\n const servers = await this.mcpdClient.get('/api/v1/servers');\n this.updateAvailableTools(servers);\n }\n ```\n4. Handle tools/list by aggregating from mcpd servers\n5. Handle resources/list and prompts/list similarly",
|
||||||
|
"testStrategy": "1. Unit test: Tool calls are forwarded to mcpd proxy correctly\n2. Unit test: Server name is extracted from namespaced tool name\n3. Integration test: Full flow Claude -> mcplocal -> mcpd -> container\n4. Test tools/list aggregates from all mcpd servers\n5. Test error handling when mcpd is unreachable\n6. Test LLM preprocessing is applied when enabled",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
"28",
|
||||||
|
"29"
|
||||||
|
],
|
||||||
|
"status": "done",
|
||||||
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T18:43:14.673Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "35",
|
||||||
|
"title": "Implement health monitoring across all tiers",
|
||||||
|
"description": "Extend health monitoring to track connectivity and status across mcplocal, mcpd, and individual MCP server instances.",
|
||||||
|
"details": "1. Update mcplocal health monitor in `src/mcplocal/src/health.ts`:\n ```typescript\n export class TieredHealthMonitor {\n async checkHealth(): Promise<TieredHealthStatus> {\n return {\n mcplocal: {\n status: 'healthy',\n llmProvider: await this.checkLlmProvider(),\n uptime: process.uptime()\n },\n mcpd: await this.checkMcpdHealth(),\n instances: await this.checkInstancesHealth()\n };\n }\n \n private async checkMcpdHealth(): Promise<McpdHealth> {\n try {\n const health = await this.mcpdClient.get('/api/v1/health');\n return { status: 'connected', ...health };\n } catch {\n return { status: 'disconnected' };\n }\n }\n \n private async checkInstancesHealth(): Promise<InstanceHealth[]> {\n const instances = await this.mcpdClient.get('/api/v1/instances');\n return instances.map(i => ({\n name: i.name,\n status: i.status,\n lastHealthCheck: i.lastHealthCheck\n }));\n }\n }\n ```\n2. Add health endpoint to mcplocal HTTP server: `GET /health`\n3. Update mcpctl status command to display tiered health\n4. Add degraded state detection:\n - LLM provider unavailable but mcpd reachable\n - Some instances down but others healthy\n5. Add health event notifications for state transitions\n6. Add configurable health check intervals",
|
||||||
|
"testStrategy": "1. Unit test: Health check correctly identifies all states\n2. Unit test: Degraded state is detected correctly\n3. Integration test: Full health check across all tiers\n4. Test health endpoint returns correct format\n5. Test mcpctl status displays health correctly\n6. Test state transition events are emitted",
|
||||||
|
"priority": "medium",
|
||||||
|
"dependencies": [
|
||||||
|
"33",
|
||||||
|
"34"
|
||||||
|
],
|
||||||
|
"status": "done",
|
||||||
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T18:46:07.885Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "36",
|
||||||
|
"title": "End-to-end integration testing",
|
||||||
|
"description": "Create comprehensive integration tests that validate the full data flow from mcpctl through mcplocal to mcpd to MCP server containers and back.",
|
||||||
|
"details": "1. Create test fixtures in `src/mcplocal/test/fixtures/`:\n - Mock MCP server that returns predictable responses\n - Test configuration files\n - Sample tool call payloads\n2. Create integration test suite in `src/mcplocal/test/integration/`:\n ```typescript\n describe('End-to-end flow', () => {\n it('mcpctl -> mcplocal -> mcpd -> mcp_server', async () => {\n // Start mock MCP server\n // Start mcpd with test config\n // Start mcplocal pointing to mcpd\n // Execute mcpctl command\n // Verify response flows back correctly\n });\n \n it('LLM pre-processing reduces response size', async () => {\n // Send query that returns large dataset\n // Verify LLM filtering reduces token count\n // Verify relevant data is preserved\n });\n \n it('credentials never leave mcpd', async () => {\n // Monitor all traffic from mcplocal\n // Verify no credentials appear in requests/responses\n });\n });\n ```\n3. Test scenarios:\n - Management commands (get servers, instances, etc.)\n - MCP tool calls with LLM preprocessing\n - MCP tool calls without preprocessing\n - Error handling (mcpd down, instance down, LLM failure)\n - Health monitoring accuracy\n4. Add CI integration test workflow\n5. Create docker-compose.test.yml for test environment",
|
||||||
|
"testStrategy": "1. All integration tests pass in CI environment\n2. Test coverage includes happy path and error scenarios\n3. Performance benchmarks: measure latency at each tier\n4. Security test: verify credential isolation\n5. Load test: multiple concurrent requests\n6. Chaos test: random component failures",
|
||||||
|
"priority": "high",
|
||||||
|
"dependencies": [
|
||||||
|
"29",
|
||||||
|
"33",
|
||||||
|
"34",
|
||||||
|
"35"
|
||||||
|
],
|
||||||
|
"status": "done",
|
||||||
|
"subtasks": [],
|
||||||
|
"updatedAt": "2026-02-21T18:52:29.084Z"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"lastModified": "2026-02-21T04:26:06.239Z",
|
"lastModified": "2026-02-21T18:52:29.084Z",
|
||||||
"taskCount": 24,
|
"taskCount": 36,
|
||||||
"completedCount": 5,
|
"completedCount": 33,
|
||||||
"tags": [
|
"tags": [
|
||||||
"master"
|
"master"
|
||||||
]
|
]
|
||||||
|
|||||||
69
cli-buildrelease.sh
Executable file
69
cli-buildrelease.sh
Executable file
@@ -0,0 +1,69 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
cd "$(dirname "$0")"
|
||||||
|
|
||||||
|
# Load .env if present
|
||||||
|
if [ -f .env ]; then
|
||||||
|
set -a; source .env; set +a
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Ensure tools are on PATH
|
||||||
|
export PATH="$HOME/.npm-global/bin:$HOME/.bun/bin:$HOME/.local/bin:$PATH"
|
||||||
|
|
||||||
|
echo "=== mcpctl CLI build & release ==="
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# 1. Build TypeScript
|
||||||
|
echo "==> Building TypeScript..."
|
||||||
|
pnpm build
|
||||||
|
|
||||||
|
# 2. Bundle standalone binary
|
||||||
|
echo "==> Bundling standalone binary..."
|
||||||
|
mkdir -p dist
|
||||||
|
rm -f dist/mcpctl dist/mcpctl-*.rpm
|
||||||
|
bun build src/cli/src/index.ts --compile --outfile dist/mcpctl
|
||||||
|
echo " Binary: $(du -h dist/mcpctl | cut -f1)"
|
||||||
|
|
||||||
|
# 3. Package RPM
|
||||||
|
echo "==> Packaging RPM..."
|
||||||
|
nfpm pkg --packager rpm --target dist/
|
||||||
|
RPM_FILE=$(ls dist/mcpctl-*.rpm 2>/dev/null | head -1)
|
||||||
|
RPM_VERSION=$(rpm -qp --queryformat '%{VERSION}-%{RELEASE}' "$RPM_FILE")
|
||||||
|
echo " RPM: $RPM_FILE ($(du -h "$RPM_FILE" | cut -f1))"
|
||||||
|
|
||||||
|
# 4. Publish to Gitea
|
||||||
|
GITEA_URL="${GITEA_URL:-http://10.0.0.194:3012}"
|
||||||
|
GITEA_OWNER="${GITEA_OWNER:-michal}"
|
||||||
|
|
||||||
|
if [ -z "$GITEA_TOKEN" ]; then
|
||||||
|
echo ""
|
||||||
|
echo "WARNING: GITEA_TOKEN not set, skipping publish. Add it to .env"
|
||||||
|
echo ""
|
||||||
|
else
|
||||||
|
echo "==> Publishing to ${GITEA_URL}..."
|
||||||
|
EXISTING=$(curl -s -o /dev/null -w "%{http_code}" \
|
||||||
|
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||||
|
"${GITEA_URL}/api/v1/packages/${GITEA_OWNER}/rpm/mcpctl/${RPM_VERSION}")
|
||||||
|
|
||||||
|
if [ "$EXISTING" = "200" ]; then
|
||||||
|
echo " Replacing existing version $RPM_VERSION..."
|
||||||
|
curl -s -o /dev/null -X DELETE \
|
||||||
|
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||||
|
"${GITEA_URL}/api/v1/packages/${GITEA_OWNER}/rpm/mcpctl/${RPM_VERSION}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
curl --fail -s -X PUT \
|
||||||
|
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||||
|
--upload-file "$RPM_FILE" \
|
||||||
|
"${GITEA_URL}/api/packages/${GITEA_OWNER}/rpm/upload"
|
||||||
|
echo " Published!"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 5. Install locally
|
||||||
|
echo "==> Installing..."
|
||||||
|
sudo rpm -U --force "$RPM_FILE"
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "=== Done ==="
|
||||||
|
mcpctl --version
|
||||||
93
completions/mcpctl.bash
Normal file
93
completions/mcpctl.bash
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
_mcpctl() {
|
||||||
|
local cur prev words cword
|
||||||
|
_init_completion || return
|
||||||
|
|
||||||
|
local commands="config status get describe instance instances apply setup claude project projects backup restore help"
|
||||||
|
local global_opts="-v --version -o --output --daemon-url -h --help"
|
||||||
|
local resources="servers profiles projects instances"
|
||||||
|
|
||||||
|
case "${words[1]}" in
|
||||||
|
config)
|
||||||
|
COMPREPLY=($(compgen -W "view set path reset help" -- "$cur"))
|
||||||
|
return ;;
|
||||||
|
status)
|
||||||
|
COMPREPLY=($(compgen -W "--daemon-url -h --help" -- "$cur"))
|
||||||
|
return ;;
|
||||||
|
get)
|
||||||
|
if [[ $cword -eq 2 ]]; then
|
||||||
|
COMPREPLY=($(compgen -W "$resources" -- "$cur"))
|
||||||
|
else
|
||||||
|
COMPREPLY=($(compgen -W "-o --output --daemon-url -h --help" -- "$cur"))
|
||||||
|
fi
|
||||||
|
return ;;
|
||||||
|
describe)
|
||||||
|
if [[ $cword -eq 2 ]]; then
|
||||||
|
COMPREPLY=($(compgen -W "$resources" -- "$cur"))
|
||||||
|
else
|
||||||
|
COMPREPLY=($(compgen -W "-o --output --daemon-url -h --help" -- "$cur"))
|
||||||
|
fi
|
||||||
|
return ;;
|
||||||
|
instance|instances)
|
||||||
|
if [[ $cword -eq 2 ]]; then
|
||||||
|
COMPREPLY=($(compgen -W "list ls start stop restart remove rm logs inspect help" -- "$cur"))
|
||||||
|
else
|
||||||
|
case "${words[2]}" in
|
||||||
|
logs)
|
||||||
|
COMPREPLY=($(compgen -W "--tail --since -h --help" -- "$cur"))
|
||||||
|
;;
|
||||||
|
start)
|
||||||
|
COMPREPLY=($(compgen -W "--env --image -h --help" -- "$cur"))
|
||||||
|
;;
|
||||||
|
list|ls)
|
||||||
|
COMPREPLY=($(compgen -W "--server-id -o --output -h --help" -- "$cur"))
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
return ;;
|
||||||
|
claude)
|
||||||
|
if [[ $cword -eq 2 ]]; then
|
||||||
|
COMPREPLY=($(compgen -W "generate show add remove help" -- "$cur"))
|
||||||
|
else
|
||||||
|
case "${words[2]}" in
|
||||||
|
generate|show|add|remove)
|
||||||
|
COMPREPLY=($(compgen -W "--path -p -h --help" -- "$cur"))
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
return ;;
|
||||||
|
project|projects)
|
||||||
|
if [[ $cword -eq 2 ]]; then
|
||||||
|
COMPREPLY=($(compgen -W "list ls create delete rm show profiles set-profiles help" -- "$cur"))
|
||||||
|
else
|
||||||
|
case "${words[2]}" in
|
||||||
|
create)
|
||||||
|
COMPREPLY=($(compgen -W "--description -d -h --help" -- "$cur"))
|
||||||
|
;;
|
||||||
|
list|ls)
|
||||||
|
COMPREPLY=($(compgen -W "-o --output -h --help" -- "$cur"))
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
return ;;
|
||||||
|
apply)
|
||||||
|
COMPREPLY=($(compgen -f -- "$cur"))
|
||||||
|
return ;;
|
||||||
|
backup)
|
||||||
|
COMPREPLY=($(compgen -W "-o --output -p --password -r --resources -h --help" -- "$cur"))
|
||||||
|
return ;;
|
||||||
|
restore)
|
||||||
|
COMPREPLY=($(compgen -W "-i --input -p --password -c --conflict -h --help" -- "$cur"))
|
||||||
|
return ;;
|
||||||
|
setup)
|
||||||
|
return ;;
|
||||||
|
help)
|
||||||
|
COMPREPLY=($(compgen -W "$commands" -- "$cur"))
|
||||||
|
return ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [[ $cword -eq 1 ]]; then
|
||||||
|
COMPREPLY=($(compgen -W "$commands $global_opts" -- "$cur"))
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
complete -F _mcpctl mcpctl
|
||||||
81
completions/mcpctl.fish
Normal file
81
completions/mcpctl.fish
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
# mcpctl fish completions
|
||||||
|
|
||||||
|
set -l commands config status get describe instance instances apply setup claude project projects backup restore help
|
||||||
|
|
||||||
|
# Disable file completions by default
|
||||||
|
complete -c mcpctl -f
|
||||||
|
|
||||||
|
# Global options
|
||||||
|
complete -c mcpctl -s v -l version -d 'Show version'
|
||||||
|
complete -c mcpctl -s o -l output -d 'Output format' -xa 'table json yaml'
|
||||||
|
complete -c mcpctl -l daemon-url -d 'mcpd daemon URL' -x
|
||||||
|
complete -c mcpctl -s h -l help -d 'Show help'
|
||||||
|
|
||||||
|
# Top-level commands
|
||||||
|
complete -c mcpctl -n "not __fish_seen_subcommand_from $commands" -a config -d 'Manage configuration'
|
||||||
|
complete -c mcpctl -n "not __fish_seen_subcommand_from $commands" -a status -d 'Show status and connectivity'
|
||||||
|
complete -c mcpctl -n "not __fish_seen_subcommand_from $commands" -a get -d 'List resources'
|
||||||
|
complete -c mcpctl -n "not __fish_seen_subcommand_from $commands" -a describe -d 'Show resource details'
|
||||||
|
complete -c mcpctl -n "not __fish_seen_subcommand_from $commands" -a instance -d 'Manage instances'
|
||||||
|
complete -c mcpctl -n "not __fish_seen_subcommand_from $commands" -a apply -d 'Apply configuration from file'
|
||||||
|
complete -c mcpctl -n "not __fish_seen_subcommand_from $commands" -a setup -d 'Interactive setup wizard'
|
||||||
|
complete -c mcpctl -n "not __fish_seen_subcommand_from $commands" -a claude -d 'Manage Claude .mcp.json'
|
||||||
|
complete -c mcpctl -n "not __fish_seen_subcommand_from $commands" -a project -d 'Manage projects'
|
||||||
|
complete -c mcpctl -n "not __fish_seen_subcommand_from $commands" -a backup -d 'Backup configuration'
|
||||||
|
complete -c mcpctl -n "not __fish_seen_subcommand_from $commands" -a restore -d 'Restore from backup'
|
||||||
|
complete -c mcpctl -n "not __fish_seen_subcommand_from $commands" -a help -d 'Show help'
|
||||||
|
|
||||||
|
# get/describe resources
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from get describe" -a 'servers profiles projects instances' -d 'Resource type'
|
||||||
|
|
||||||
|
# config subcommands
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from config; and not __fish_seen_subcommand_from view set path reset" -a view -d 'Show configuration'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from config; and not __fish_seen_subcommand_from view set path reset" -a set -d 'Set a config value'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from config; and not __fish_seen_subcommand_from view set path reset" -a path -d 'Show config file path'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from config; and not __fish_seen_subcommand_from view set path reset" -a reset -d 'Reset to defaults'
|
||||||
|
|
||||||
|
# instance subcommands
|
||||||
|
set -l instance_cmds list ls start stop restart remove rm logs inspect
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from instance instances; and not __fish_seen_subcommand_from $instance_cmds" -a list -d 'List instances'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from instance instances; and not __fish_seen_subcommand_from $instance_cmds" -a start -d 'Start instance'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from instance instances; and not __fish_seen_subcommand_from $instance_cmds" -a stop -d 'Stop instance'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from instance instances; and not __fish_seen_subcommand_from $instance_cmds" -a restart -d 'Restart instance'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from instance instances; and not __fish_seen_subcommand_from $instance_cmds" -a remove -d 'Remove instance'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from instance instances; and not __fish_seen_subcommand_from $instance_cmds" -a logs -d 'Get logs'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from instance instances; and not __fish_seen_subcommand_from $instance_cmds" -a inspect -d 'Inspect container'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from instance instances; and __fish_seen_subcommand_from logs" -l tail -d 'Number of lines' -x
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from instance instances; and __fish_seen_subcommand_from logs" -l since -d 'Since timestamp' -x
|
||||||
|
|
||||||
|
# claude subcommands
|
||||||
|
set -l claude_cmds generate show add remove
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from claude; and not __fish_seen_subcommand_from $claude_cmds" -a generate -d 'Generate .mcp.json'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from claude; and not __fish_seen_subcommand_from $claude_cmds" -a show -d 'Show .mcp.json'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from claude; and not __fish_seen_subcommand_from $claude_cmds" -a add -d 'Add server entry'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from claude; and not __fish_seen_subcommand_from $claude_cmds" -a remove -d 'Remove server entry'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from claude; and __fish_seen_subcommand_from $claude_cmds" -s p -l path -d 'Path to .mcp.json' -rF
|
||||||
|
|
||||||
|
# project subcommands
|
||||||
|
set -l project_cmds list ls create delete rm show profiles set-profiles
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from project projects; and not __fish_seen_subcommand_from $project_cmds" -a list -d 'List projects'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from project projects; and not __fish_seen_subcommand_from $project_cmds" -a create -d 'Create project'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from project projects; and not __fish_seen_subcommand_from $project_cmds" -a delete -d 'Delete project'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from project projects; and not __fish_seen_subcommand_from $project_cmds" -a show -d 'Show project'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from project projects; and not __fish_seen_subcommand_from $project_cmds" -a profiles -d 'List profiles'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from project projects; and not __fish_seen_subcommand_from $project_cmds" -a set-profiles -d 'Set profiles'
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from project projects; and __fish_seen_subcommand_from create" -s d -l description -d 'Description' -x
|
||||||
|
|
||||||
|
# backup options
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from backup" -s o -l output -d 'Output file' -rF
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from backup" -s p -l password -d 'Encryption password' -x
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from backup" -s r -l resources -d 'Resources to backup' -xa 'servers profiles projects'
|
||||||
|
|
||||||
|
# restore options
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from restore" -s i -l input -d 'Input file' -rF
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from restore" -s p -l password -d 'Decryption password' -x
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from restore" -s c -l conflict -d 'Conflict strategy' -xa 'skip overwrite fail'
|
||||||
|
|
||||||
|
# apply takes a file
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from apply" -F
|
||||||
|
|
||||||
|
# help completions
|
||||||
|
complete -c mcpctl -n "__fish_seen_subcommand_from help" -a "$commands"
|
||||||
61
deploy/Dockerfile.mcpd
Normal file
61
deploy/Dockerfile.mcpd
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
# Stage 1: Build TypeScript
|
||||||
|
FROM node:20-alpine AS builder
|
||||||
|
|
||||||
|
RUN corepack enable && corepack prepare pnpm@9.15.0 --activate
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy workspace config and package manifests
|
||||||
|
COPY pnpm-workspace.yaml pnpm-lock.yaml package.json tsconfig.base.json ./
|
||||||
|
COPY src/mcpd/package.json src/mcpd/tsconfig.json src/mcpd/
|
||||||
|
COPY src/db/package.json src/db/tsconfig.json src/db/
|
||||||
|
COPY src/shared/package.json src/shared/tsconfig.json src/shared/
|
||||||
|
|
||||||
|
# Install all dependencies
|
||||||
|
RUN pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
# Copy source code
|
||||||
|
COPY src/mcpd/src/ src/mcpd/src/
|
||||||
|
COPY src/db/src/ src/db/src/
|
||||||
|
COPY src/db/prisma/ src/db/prisma/
|
||||||
|
COPY src/shared/src/ src/shared/src/
|
||||||
|
|
||||||
|
# Generate Prisma client and build TypeScript
|
||||||
|
RUN pnpm -F @mcpctl/db db:generate
|
||||||
|
RUN pnpm -F @mcpctl/shared build && pnpm -F @mcpctl/db build && pnpm -F @mcpctl/mcpd build
|
||||||
|
|
||||||
|
# Stage 2: Production runtime
|
||||||
|
FROM node:20-alpine
|
||||||
|
|
||||||
|
RUN corepack enable && corepack prepare pnpm@9.15.0 --activate
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy workspace config, manifests, and lockfile
|
||||||
|
COPY pnpm-workspace.yaml pnpm-lock.yaml package.json ./
|
||||||
|
COPY src/mcpd/package.json src/mcpd/
|
||||||
|
COPY src/db/package.json src/db/
|
||||||
|
COPY src/shared/package.json src/shared/
|
||||||
|
|
||||||
|
# Install all deps (prisma CLI needed at runtime for db push)
|
||||||
|
RUN pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
# Copy prisma schema and generate client
|
||||||
|
COPY src/db/prisma/ src/db/prisma/
|
||||||
|
RUN pnpm -F @mcpctl/db db:generate
|
||||||
|
|
||||||
|
# Copy built output from builder
|
||||||
|
COPY --from=builder /app/src/shared/dist/ src/shared/dist/
|
||||||
|
COPY --from=builder /app/src/db/dist/ src/db/dist/
|
||||||
|
COPY --from=builder /app/src/mcpd/dist/ src/mcpd/dist/
|
||||||
|
|
||||||
|
# Copy entrypoint
|
||||||
|
COPY deploy/entrypoint.sh /entrypoint.sh
|
||||||
|
RUN chmod +x /entrypoint.sh
|
||||||
|
|
||||||
|
EXPOSE 3100
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=10s --timeout=5s --retries=3 --start-period=10s \
|
||||||
|
CMD wget -q --spider http://localhost:3100/healthz || exit 1
|
||||||
|
|
||||||
|
ENTRYPOINT ["/entrypoint.sh"]
|
||||||
@@ -27,14 +27,17 @@ services:
|
|||||||
- "3100:3100"
|
- "3100:3100"
|
||||||
environment:
|
environment:
|
||||||
DATABASE_URL: postgresql://mcpctl:mcpctl_dev@postgres:5432/mcpctl
|
DATABASE_URL: postgresql://mcpctl:mcpctl_dev@postgres:5432/mcpctl
|
||||||
PORT: "3100"
|
MCPD_PORT: "3100"
|
||||||
HOST: "0.0.0.0"
|
MCPD_HOST: "0.0.0.0"
|
||||||
LOG_LEVEL: info
|
MCPD_LOG_LEVEL: info
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
volumes:
|
volumes:
|
||||||
- /var/run/docker.sock:/var/run/docker.sock
|
# Mount container runtime socket (Docker or Podman)
|
||||||
|
# For Docker: /var/run/docker.sock
|
||||||
|
# For Podman: /run/user/<UID>/podman/podman.sock
|
||||||
|
- ${CONTAINER_SOCK:-/var/run/docker.sock}:/var/run/docker.sock
|
||||||
networks:
|
networks:
|
||||||
- mcpctl
|
- mcpctl
|
||||||
- mcp-servers
|
- mcp-servers
|
||||||
|
|||||||
11
deploy/entrypoint.sh
Executable file
11
deploy/entrypoint.sh
Executable file
@@ -0,0 +1,11 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -e
|
||||||
|
|
||||||
|
echo "mcpd: pushing database schema..."
|
||||||
|
pnpm -F @mcpctl/db exec prisma db push --schema=prisma/schema.prisma --accept-data-loss 2>&1
|
||||||
|
|
||||||
|
echo "mcpd: seeding default data..."
|
||||||
|
node src/mcpd/dist/seed-runner.js
|
||||||
|
|
||||||
|
echo "mcpd: starting server..."
|
||||||
|
exec node src/mcpd/dist/main.js
|
||||||
149
docs/architecture.md
Normal file
149
docs/architecture.md
Normal file
@@ -0,0 +1,149 @@
|
|||||||
|
# mcpctl Architecture
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
mcpctl is a kubectl-like management tool for MCP (Model Context Protocol) servers. It consists of a CLI, a daemon server, a database layer, a local proxy, and shared utilities.
|
||||||
|
|
||||||
|
## Package Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
├── cli/ @mcpctl/cli - Command-line interface
|
||||||
|
├── mcpd/ @mcpctl/mcpd - Daemon server (REST API)
|
||||||
|
├── db/ @mcpctl/db - Database layer (Prisma + PostgreSQL)
|
||||||
|
├── local-proxy/ @mcpctl/local-proxy - MCP protocol proxy
|
||||||
|
└── shared/ @mcpctl/shared - Shared constants and utilities
|
||||||
|
```
|
||||||
|
|
||||||
|
## Component Diagram
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────┐ HTTP ┌──────────────┐ Prisma ┌────────────┐
|
||||||
|
│ mcpctl CLI │ ──────────────│ mcpd │ ──────────────│ PostgreSQL │
|
||||||
|
│ (Commander.js) │ │ (Fastify 5) │ │ │
|
||||||
|
└─────────────────┘ └──────┬───────┘ └────────────┘
|
||||||
|
│
|
||||||
|
│ Docker/Podman API
|
||||||
|
▼
|
||||||
|
┌──────────────┐
|
||||||
|
│ Containers │
|
||||||
|
│ (MCP servers)│
|
||||||
|
└──────────────┘
|
||||||
|
|
||||||
|
┌─────────────────┐ STDIO ┌──────────────┐ STDIO/HTTP ┌────────────┐
|
||||||
|
│ Claude / LLM │ ────────────│ local-proxy │ ──────────────│ MCP Servers│
|
||||||
|
│ │ │ (McpRouter) │ │ │
|
||||||
|
└─────────────────┘ └──────────────┘ └────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## CLI (`@mcpctl/cli`)
|
||||||
|
|
||||||
|
The CLI is built with Commander.js and communicates with mcpd via HTTP REST.
|
||||||
|
|
||||||
|
### Commands
|
||||||
|
|
||||||
|
| Command | Description |
|
||||||
|
|---------|-------------|
|
||||||
|
| `mcpctl get <resource>` | List resources (servers, profiles, projects, instances) |
|
||||||
|
| `mcpctl describe <resource> <id>` | Show detailed resource info |
|
||||||
|
| `mcpctl apply <file>` | Apply declarative YAML/JSON configuration |
|
||||||
|
| `mcpctl setup [name]` | Interactive server setup wizard |
|
||||||
|
| `mcpctl instance list/start/stop/restart/remove/logs/inspect` | Manage instances |
|
||||||
|
| `mcpctl claude generate/show/add/remove` | Manage .mcp.json files |
|
||||||
|
| `mcpctl project list/create/delete/show/profiles/set-profiles` | Manage projects |
|
||||||
|
| `mcpctl config get/set/path` | Manage CLI configuration |
|
||||||
|
| `mcpctl status` | Check daemon connectivity |
|
||||||
|
|
||||||
|
### Configuration
|
||||||
|
|
||||||
|
CLI config is stored at `~/.config/mcpctl/config.json` with:
|
||||||
|
- `daemonUrl`: mcpd server URL (default: `http://localhost:4444`)
|
||||||
|
|
||||||
|
## Daemon (`@mcpctl/mcpd`)
|
||||||
|
|
||||||
|
Fastify 5-based REST API server that manages MCP server lifecycle.
|
||||||
|
|
||||||
|
### Layers
|
||||||
|
|
||||||
|
1. **Routes** - HTTP handlers, parameter extraction
|
||||||
|
2. **Services** - Business logic, validation (Zod schemas), error handling
|
||||||
|
3. **Repositories** - Data access via Prisma (interface-based for testability)
|
||||||
|
|
||||||
|
### API Endpoints
|
||||||
|
|
||||||
|
| Endpoint | Methods | Description |
|
||||||
|
|----------|---------|-------------|
|
||||||
|
| `/api/v1/servers` | GET, POST | MCP server definitions |
|
||||||
|
| `/api/v1/servers/:id` | GET, PUT, DELETE | Single server operations |
|
||||||
|
| `/api/v1/profiles` | GET, POST | Server configuration profiles |
|
||||||
|
| `/api/v1/profiles/:id` | GET, PUT, DELETE | Single profile operations |
|
||||||
|
| `/api/v1/projects` | GET, POST | Project management |
|
||||||
|
| `/api/v1/projects/:id` | GET, PUT, DELETE | Single project operations |
|
||||||
|
| `/api/v1/projects/:id/profiles` | GET, PUT | Project profile assignments |
|
||||||
|
| `/api/v1/projects/:id/mcp-config` | GET | Generate .mcp.json |
|
||||||
|
| `/api/v1/instances` | GET, POST | Instance lifecycle |
|
||||||
|
| `/api/v1/instances/:id` | GET, DELETE | Instance operations |
|
||||||
|
| `/api/v1/instances/:id/stop` | POST | Stop instance |
|
||||||
|
| `/api/v1/instances/:id/restart` | POST | Restart instance |
|
||||||
|
| `/api/v1/instances/:id/inspect` | GET | Container inspection |
|
||||||
|
| `/api/v1/instances/:id/logs` | GET | Container logs |
|
||||||
|
| `/api/v1/audit-logs` | GET | Query audit logs |
|
||||||
|
| `/api/v1/audit-logs/:id` | GET | Single audit log |
|
||||||
|
| `/api/v1/audit-logs/purge` | POST | Purge expired logs |
|
||||||
|
| `/health` | GET | Health check (detailed) |
|
||||||
|
| `/healthz` | GET | Liveness probe |
|
||||||
|
|
||||||
|
### Container Orchestration
|
||||||
|
|
||||||
|
The `McpOrchestrator` interface abstracts container management:
|
||||||
|
- `DockerContainerManager` - Docker/Podman implementation via dockerode
|
||||||
|
- Future: `KubernetesOrchestrator` for k8s deployments
|
||||||
|
|
||||||
|
## Local Proxy (`@mcpctl/local-proxy`)
|
||||||
|
|
||||||
|
Aggregates multiple MCP servers behind a single STDIO endpoint.
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **Tool namespacing**: `servername/toolname` routing
|
||||||
|
- **Resource forwarding**: `resources/list` and `resources/read`
|
||||||
|
- **Prompt forwarding**: `prompts/list` and `prompts/get`
|
||||||
|
- **Notification pass-through**: Upstream notifications forwarded to client
|
||||||
|
- **Health monitoring**: Periodic health checks with state tracking
|
||||||
|
- **Transport support**: STDIO (child process) and HTTP (SSE/Streamable HTTP)
|
||||||
|
|
||||||
|
### Usage
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Via config file
|
||||||
|
mcpctl-proxy --config proxy.json
|
||||||
|
|
||||||
|
# Via CLI flags
|
||||||
|
mcpctl-proxy --upstream "slack:npx -y @anthropic/slack-mcp" \
|
||||||
|
--upstream "github:npx -y @anthropic/github-mcp"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Database (`@mcpctl/db`)
|
||||||
|
|
||||||
|
Prisma ORM with PostgreSQL. Key models:
|
||||||
|
|
||||||
|
- **User** / **Session** - Authentication
|
||||||
|
- **McpServer** - Server definitions (name, transport, package, docker image)
|
||||||
|
- **McpProfile** - Per-server configurations (env overrides, permissions)
|
||||||
|
- **Project** - Grouping of profiles for a workspace
|
||||||
|
- **McpInstance** - Running container instances with lifecycle state
|
||||||
|
- **AuditLog** - Immutable operation audit trail
|
||||||
|
|
||||||
|
## Shared (`@mcpctl/shared`)
|
||||||
|
|
||||||
|
Constants and utilities shared across packages:
|
||||||
|
- `APP_NAME`, `APP_VERSION`
|
||||||
|
- Common type definitions
|
||||||
|
|
||||||
|
## Design Principles
|
||||||
|
|
||||||
|
1. **Interface-based repositories** - All data access through interfaces for testability
|
||||||
|
2. **Dependency injection** - Services receive dependencies via constructor
|
||||||
|
3. **Zod validation** - All user input validated with Zod schemas
|
||||||
|
4. **Namespaced errors** - Custom error classes with HTTP status codes
|
||||||
|
5. **TypeScript strict mode** - `exactOptionalPropertyTypes`, `noUncheckedIndexedAccess`
|
||||||
155
docs/getting-started.md
Normal file
155
docs/getting-started.md
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
# Getting Started with mcpctl
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- Node.js >= 20.0.0
|
||||||
|
- pnpm >= 9.0.0
|
||||||
|
- PostgreSQL (for mcpd)
|
||||||
|
- Docker or Podman (for container management)
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Clone the repository
|
||||||
|
git clone <repo-url>
|
||||||
|
cd mcpctl
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
pnpm install
|
||||||
|
|
||||||
|
# Generate Prisma client
|
||||||
|
pnpm --filter @mcpctl/db exec prisma generate
|
||||||
|
|
||||||
|
# Build all packages
|
||||||
|
pnpm build
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### 1. Start the Database
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Start PostgreSQL via Docker Compose
|
||||||
|
pnpm db:up
|
||||||
|
|
||||||
|
# Run database migrations
|
||||||
|
pnpm --filter @mcpctl/db exec prisma db push
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Start the Daemon
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd src/mcpd
|
||||||
|
pnpm dev
|
||||||
|
```
|
||||||
|
|
||||||
|
The daemon starts on `http://localhost:4444` by default.
|
||||||
|
|
||||||
|
### 3. Use the CLI
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Check daemon status
|
||||||
|
mcpctl status
|
||||||
|
|
||||||
|
# Register an MCP server
|
||||||
|
mcpctl apply config.yaml
|
||||||
|
|
||||||
|
# Or use the interactive wizard
|
||||||
|
mcpctl setup my-server
|
||||||
|
|
||||||
|
# List registered servers
|
||||||
|
mcpctl get servers
|
||||||
|
|
||||||
|
# Start an instance
|
||||||
|
mcpctl instance start <server-id>
|
||||||
|
|
||||||
|
# Check instance status
|
||||||
|
mcpctl instance list
|
||||||
|
|
||||||
|
# View instance logs
|
||||||
|
mcpctl instance logs <instance-id>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Generate .mcp.json for Claude
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Create a project
|
||||||
|
mcpctl project create my-workspace
|
||||||
|
|
||||||
|
# Assign profiles to project
|
||||||
|
mcpctl project set-profiles <project-id> <profile-id-1> <profile-id-2>
|
||||||
|
|
||||||
|
# Generate .mcp.json
|
||||||
|
mcpctl claude generate <project-id>
|
||||||
|
|
||||||
|
# Or manually add servers
|
||||||
|
mcpctl claude add my-server -c npx -a -y @my/mcp-server
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example Configuration
|
||||||
|
|
||||||
|
Create a `config.yaml` file:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
servers:
|
||||||
|
- name: slack
|
||||||
|
description: Slack MCP server
|
||||||
|
transport: STDIO
|
||||||
|
packageName: "@anthropic/slack-mcp"
|
||||||
|
envTemplate:
|
||||||
|
- name: SLACK_TOKEN
|
||||||
|
description: Slack bot token
|
||||||
|
isSecret: true
|
||||||
|
|
||||||
|
- name: github
|
||||||
|
description: GitHub MCP server
|
||||||
|
transport: STDIO
|
||||||
|
packageName: "@anthropic/github-mcp"
|
||||||
|
|
||||||
|
profiles:
|
||||||
|
- name: default
|
||||||
|
server: slack
|
||||||
|
envOverrides:
|
||||||
|
SLACK_TOKEN: "xoxb-your-token"
|
||||||
|
|
||||||
|
projects:
|
||||||
|
- name: dev-workspace
|
||||||
|
description: Development workspace
|
||||||
|
```
|
||||||
|
|
||||||
|
Apply it:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mcpctl apply config.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
## Running Tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Run all tests
|
||||||
|
pnpm test:run
|
||||||
|
|
||||||
|
# Run tests for a specific package
|
||||||
|
pnpm --filter @mcpctl/cli test:run
|
||||||
|
pnpm --filter @mcpctl/mcpd test:run
|
||||||
|
pnpm --filter @mcpctl/local-proxy test:run
|
||||||
|
|
||||||
|
# Run tests with coverage
|
||||||
|
pnpm test:coverage
|
||||||
|
|
||||||
|
# Typecheck
|
||||||
|
pnpm typecheck
|
||||||
|
|
||||||
|
# Lint
|
||||||
|
pnpm lint
|
||||||
|
```
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Watch mode for tests
|
||||||
|
pnpm test
|
||||||
|
|
||||||
|
# Build in watch mode
|
||||||
|
cd src/cli && pnpm dev
|
||||||
|
```
|
||||||
26
examples/ha-mcp.yaml
Normal file
26
examples/ha-mcp.yaml
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
servers:
|
||||||
|
- name: ha-mcp
|
||||||
|
description: "Home Assistant MCP - smart home control via MCP"
|
||||||
|
dockerImage: "ghcr.io/homeassistant-ai/ha-mcp:2.4"
|
||||||
|
transport: STREAMABLE_HTTP
|
||||||
|
containerPort: 3000
|
||||||
|
# For mcpd-managed containers:
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- "-c"
|
||||||
|
- "from ha_mcp.server import HomeAssistantSmartMCPServer; s = HomeAssistantSmartMCPServer(); s.mcp.run(transport='sse', host='0.0.0.0', port=3000)"
|
||||||
|
# For connecting to an already-running instance (host.containers.internal for container-to-host):
|
||||||
|
externalUrl: "http://host.containers.internal:8086/mcp"
|
||||||
|
envTemplate:
|
||||||
|
- name: HOMEASSISTANT_URL
|
||||||
|
description: "Home Assistant instance URL (e.g. https://ha.example.com)"
|
||||||
|
- name: HOMEASSISTANT_TOKEN
|
||||||
|
description: "Home Assistant long-lived access token"
|
||||||
|
isSecret: true
|
||||||
|
|
||||||
|
profiles:
|
||||||
|
- name: production
|
||||||
|
server: ha-mcp
|
||||||
|
envOverrides:
|
||||||
|
HOMEASSISTANT_URL: "https://ha.itaz.eu"
|
||||||
|
HOMEASSISTANT_TOKEN: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiIyNjFlZTRhOWI2MGM0YTllOGJkNTIxN2Q3YmVmZDkzNSIsImlhdCI6MTc3MDA3NjYzOCwiZXhwIjoyMDg1NDM2NjM4fQ.17mAQxIrCBrQx3ogqAUetwEt-cngRmJiH-e7sLt-3FY"
|
||||||
20
nfpm.yaml
Normal file
20
nfpm.yaml
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
name: mcpctl
|
||||||
|
arch: amd64
|
||||||
|
version: 0.1.0
|
||||||
|
release: "1"
|
||||||
|
maintainer: michal
|
||||||
|
description: kubectl-like CLI for managing MCP servers
|
||||||
|
license: MIT
|
||||||
|
contents:
|
||||||
|
- src: ./dist/mcpctl
|
||||||
|
dst: /usr/bin/mcpctl
|
||||||
|
file_info:
|
||||||
|
mode: 0755
|
||||||
|
- src: ./completions/mcpctl.bash
|
||||||
|
dst: /usr/share/bash-completion/completions/mcpctl
|
||||||
|
file_info:
|
||||||
|
mode: 0644
|
||||||
|
- src: ./completions/mcpctl.fish
|
||||||
|
dst: /usr/share/fish/vendor_completions.d/mcpctl.fish
|
||||||
|
file_info:
|
||||||
|
mode: 0644
|
||||||
@@ -15,7 +15,10 @@
|
|||||||
"clean": "pnpm -r run clean && rimraf node_modules",
|
"clean": "pnpm -r run clean && rimraf node_modules",
|
||||||
"db:up": "docker compose -f deploy/docker-compose.yml up -d",
|
"db:up": "docker compose -f deploy/docker-compose.yml up -d",
|
||||||
"db:down": "docker compose -f deploy/docker-compose.yml down",
|
"db:down": "docker compose -f deploy/docker-compose.yml down",
|
||||||
"typecheck": "tsc --build"
|
"typecheck": "tsc --build",
|
||||||
|
"rpm:build": "bash scripts/build-rpm.sh",
|
||||||
|
"rpm:publish": "bash scripts/publish-rpm.sh",
|
||||||
|
"release": "bash scripts/release.sh"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.0.0",
|
"node": ">=20.0.0",
|
||||||
|
|||||||
369
pnpm-lock.yaml
generated
369
pnpm-lock.yaml
generated
@@ -83,15 +83,6 @@ importers:
|
|||||||
specifier: ^6.0.0
|
specifier: ^6.0.0
|
||||||
version: 6.19.2(typescript@5.9.3)
|
version: 6.19.2(typescript@5.9.3)
|
||||||
|
|
||||||
src/local-proxy:
|
|
||||||
dependencies:
|
|
||||||
'@mcpctl/shared':
|
|
||||||
specifier: workspace:*
|
|
||||||
version: link:../shared
|
|
||||||
'@modelcontextprotocol/sdk':
|
|
||||||
specifier: ^1.0.0
|
|
||||||
version: 1.26.0(zod@3.25.76)
|
|
||||||
|
|
||||||
src/mcpd:
|
src/mcpd:
|
||||||
dependencies:
|
dependencies:
|
||||||
'@fastify/cors':
|
'@fastify/cors':
|
||||||
@@ -112,6 +103,9 @@ importers:
|
|||||||
'@prisma/client':
|
'@prisma/client':
|
||||||
specifier: ^6.0.0
|
specifier: ^6.0.0
|
||||||
version: 6.19.2(prisma@6.19.2(typescript@5.9.3))(typescript@5.9.3)
|
version: 6.19.2(prisma@6.19.2(typescript@5.9.3))(typescript@5.9.3)
|
||||||
|
bcrypt:
|
||||||
|
specifier: ^5.1.1
|
||||||
|
version: 5.1.1
|
||||||
dockerode:
|
dockerode:
|
||||||
specifier: ^4.0.9
|
specifier: ^4.0.9
|
||||||
version: 4.0.9
|
version: 4.0.9
|
||||||
@@ -122,6 +116,9 @@ importers:
|
|||||||
specifier: ^3.24.0
|
specifier: ^3.24.0
|
||||||
version: 3.25.76
|
version: 3.25.76
|
||||||
devDependencies:
|
devDependencies:
|
||||||
|
'@types/bcrypt':
|
||||||
|
specifier: ^5.0.2
|
||||||
|
version: 5.0.2
|
||||||
'@types/dockerode':
|
'@types/dockerode':
|
||||||
specifier: ^4.0.1
|
specifier: ^4.0.1
|
||||||
version: 4.0.1
|
version: 4.0.1
|
||||||
@@ -129,6 +126,25 @@ importers:
|
|||||||
specifier: ^25.3.0
|
specifier: ^25.3.0
|
||||||
version: 25.3.0
|
version: 25.3.0
|
||||||
|
|
||||||
|
src/mcplocal:
|
||||||
|
dependencies:
|
||||||
|
'@fastify/cors':
|
||||||
|
specifier: ^10.0.0
|
||||||
|
version: 10.1.0
|
||||||
|
'@mcpctl/shared':
|
||||||
|
specifier: workspace:*
|
||||||
|
version: link:../shared
|
||||||
|
'@modelcontextprotocol/sdk':
|
||||||
|
specifier: ^1.0.0
|
||||||
|
version: 1.26.0(zod@3.25.76)
|
||||||
|
fastify:
|
||||||
|
specifier: ^5.0.0
|
||||||
|
version: 5.7.4
|
||||||
|
devDependencies:
|
||||||
|
'@types/node':
|
||||||
|
specifier: ^25.3.0
|
||||||
|
version: 25.3.0
|
||||||
|
|
||||||
src/shared:
|
src/shared:
|
||||||
dependencies:
|
dependencies:
|
||||||
zod:
|
zod:
|
||||||
@@ -561,6 +577,10 @@ packages:
|
|||||||
resolution: {integrity: sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==}
|
resolution: {integrity: sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==}
|
||||||
engines: {node: '>=8'}
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
|
'@mapbox/node-pre-gyp@1.0.11':
|
||||||
|
resolution: {integrity: sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
'@modelcontextprotocol/sdk@1.26.0':
|
'@modelcontextprotocol/sdk@1.26.0':
|
||||||
resolution: {integrity: sha512-Y5RmPncpiDtTXDbLKswIJzTqu2hyBKxTNsgKqKclDbhIgg1wgtf1fRuvxgTnRfcnxtvvgbIEcqUOzZrJ6iSReg==}
|
resolution: {integrity: sha512-Y5RmPncpiDtTXDbLKswIJzTqu2hyBKxTNsgKqKclDbhIgg1wgtf1fRuvxgTnRfcnxtvvgbIEcqUOzZrJ6iSReg==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
@@ -762,6 +782,9 @@ packages:
|
|||||||
'@standard-schema/spec@1.1.0':
|
'@standard-schema/spec@1.1.0':
|
||||||
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
|
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
|
||||||
|
|
||||||
|
'@types/bcrypt@5.0.2':
|
||||||
|
resolution: {integrity: sha512-6atioO8Y75fNcbmj0G7UjI9lXN2pQ/IGJ2FWT4a/btd0Lk9lQalHLKhkgKVZ3r+spnmWUKfbMi1GEe9wyHQfNQ==}
|
||||||
|
|
||||||
'@types/chai@5.2.3':
|
'@types/chai@5.2.3':
|
||||||
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
|
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
|
||||||
|
|
||||||
@@ -892,6 +915,9 @@ packages:
|
|||||||
'@vitest/utils@4.0.18':
|
'@vitest/utils@4.0.18':
|
||||||
resolution: {integrity: sha512-msMRKLMVLWygpK3u2Hybgi4MNjcYJvwTb0Ru09+fOyCXIgT5raYP041DRRdiJiI3k/2U6SEbAETB3YtBrUkCFA==}
|
resolution: {integrity: sha512-msMRKLMVLWygpK3u2Hybgi4MNjcYJvwTb0Ru09+fOyCXIgT5raYP041DRRdiJiI3k/2U6SEbAETB3YtBrUkCFA==}
|
||||||
|
|
||||||
|
abbrev@1.1.1:
|
||||||
|
resolution: {integrity: sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==}
|
||||||
|
|
||||||
abstract-logging@2.0.1:
|
abstract-logging@2.0.1:
|
||||||
resolution: {integrity: sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==}
|
resolution: {integrity: sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==}
|
||||||
|
|
||||||
@@ -909,6 +935,10 @@ packages:
|
|||||||
engines: {node: '>=0.4.0'}
|
engines: {node: '>=0.4.0'}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
|
agent-base@6.0.2:
|
||||||
|
resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}
|
||||||
|
engines: {node: '>= 6.0.0'}
|
||||||
|
|
||||||
ajv-formats@3.0.1:
|
ajv-formats@3.0.1:
|
||||||
resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==}
|
resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
@@ -931,6 +961,14 @@ packages:
|
|||||||
resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}
|
resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}
|
||||||
engines: {node: '>=8'}
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
|
aproba@2.1.0:
|
||||||
|
resolution: {integrity: sha512-tLIEcj5GuR2RSTnxNKdkK0dJ/GrC7P38sUkiDmDuHfsHmbagTFAxDVIBltoklXEVIQ/f14IL8IMJ5pn9Hez1Ew==}
|
||||||
|
|
||||||
|
are-we-there-yet@2.0.0:
|
||||||
|
resolution: {integrity: sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==}
|
||||||
|
engines: {node: '>=10'}
|
||||||
|
deprecated: This package is no longer supported.
|
||||||
|
|
||||||
argparse@2.0.1:
|
argparse@2.0.1:
|
||||||
resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}
|
resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}
|
||||||
|
|
||||||
@@ -964,6 +1002,10 @@ packages:
|
|||||||
bcrypt-pbkdf@1.0.2:
|
bcrypt-pbkdf@1.0.2:
|
||||||
resolution: {integrity: sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==}
|
resolution: {integrity: sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==}
|
||||||
|
|
||||||
|
bcrypt@5.1.1:
|
||||||
|
resolution: {integrity: sha512-AGBHOG5hPYZ5Xl9KXzU5iKq9516yEmvCKDg3ecP5kX2aB6UqTeXZxk2ELnDgDm6BQSMlLt9rDB4LoSMx0rYwww==}
|
||||||
|
engines: {node: '>= 10.0.0'}
|
||||||
|
|
||||||
bl@4.1.0:
|
bl@4.1.0:
|
||||||
resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==}
|
resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==}
|
||||||
|
|
||||||
@@ -971,6 +1013,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==}
|
resolution: {integrity: sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
|
brace-expansion@1.1.12:
|
||||||
|
resolution: {integrity: sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==}
|
||||||
|
|
||||||
brace-expansion@2.0.2:
|
brace-expansion@2.0.2:
|
||||||
resolution: {integrity: sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==}
|
resolution: {integrity: sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==}
|
||||||
|
|
||||||
@@ -1023,6 +1068,10 @@ packages:
|
|||||||
chownr@1.1.4:
|
chownr@1.1.4:
|
||||||
resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==}
|
resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==}
|
||||||
|
|
||||||
|
chownr@2.0.0:
|
||||||
|
resolution: {integrity: sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==}
|
||||||
|
engines: {node: '>=10'}
|
||||||
|
|
||||||
citty@0.1.6:
|
citty@0.1.6:
|
||||||
resolution: {integrity: sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ==}
|
resolution: {integrity: sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ==}
|
||||||
|
|
||||||
@@ -1044,10 +1093,17 @@ packages:
|
|||||||
color-name@1.1.4:
|
color-name@1.1.4:
|
||||||
resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
|
resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
|
||||||
|
|
||||||
|
color-support@1.1.3:
|
||||||
|
resolution: {integrity: sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
commander@13.1.0:
|
commander@13.1.0:
|
||||||
resolution: {integrity: sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==}
|
resolution: {integrity: sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
|
concat-map@0.0.1:
|
||||||
|
resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==}
|
||||||
|
|
||||||
confbox@0.2.4:
|
confbox@0.2.4:
|
||||||
resolution: {integrity: sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==}
|
resolution: {integrity: sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==}
|
||||||
|
|
||||||
@@ -1055,6 +1111,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==}
|
resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==}
|
||||||
engines: {node: ^14.18.0 || >=16.10.0}
|
engines: {node: ^14.18.0 || >=16.10.0}
|
||||||
|
|
||||||
|
console-control-strings@1.1.0:
|
||||||
|
resolution: {integrity: sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==}
|
||||||
|
|
||||||
content-disposition@1.0.1:
|
content-disposition@1.0.1:
|
||||||
resolution: {integrity: sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==}
|
resolution: {integrity: sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
@@ -1106,6 +1165,9 @@ packages:
|
|||||||
defu@6.1.4:
|
defu@6.1.4:
|
||||||
resolution: {integrity: sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==}
|
resolution: {integrity: sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==}
|
||||||
|
|
||||||
|
delegates@1.0.0:
|
||||||
|
resolution: {integrity: sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==}
|
||||||
|
|
||||||
depd@2.0.0:
|
depd@2.0.0:
|
||||||
resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}
|
resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}
|
||||||
engines: {node: '>= 0.8'}
|
engines: {node: '>= 0.8'}
|
||||||
@@ -1117,6 +1179,10 @@ packages:
|
|||||||
destr@2.0.5:
|
destr@2.0.5:
|
||||||
resolution: {integrity: sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==}
|
resolution: {integrity: sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==}
|
||||||
|
|
||||||
|
detect-libc@2.1.2:
|
||||||
|
resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
|
||||||
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
docker-modem@5.0.6:
|
docker-modem@5.0.6:
|
||||||
resolution: {integrity: sha512-ens7BiayssQz/uAxGzH8zGXCtiV24rRWXdjNha5V4zSOcxmAZsfGVm/PPFbwQdqEkDnhG+SyR9E3zSHUbOKXBQ==}
|
resolution: {integrity: sha512-ens7BiayssQz/uAxGzH8zGXCtiV24rRWXdjNha5V4zSOcxmAZsfGVm/PPFbwQdqEkDnhG+SyR9E3zSHUbOKXBQ==}
|
||||||
engines: {node: '>= 8.0'}
|
engines: {node: '>= 8.0'}
|
||||||
@@ -1341,6 +1407,13 @@ packages:
|
|||||||
fs-constants@1.0.0:
|
fs-constants@1.0.0:
|
||||||
resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}
|
resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}
|
||||||
|
|
||||||
|
fs-minipass@2.1.0:
|
||||||
|
resolution: {integrity: sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==}
|
||||||
|
engines: {node: '>= 8'}
|
||||||
|
|
||||||
|
fs.realpath@1.0.0:
|
||||||
|
resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==}
|
||||||
|
|
||||||
fsevents@2.3.3:
|
fsevents@2.3.3:
|
||||||
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
|
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
|
||||||
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
|
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
|
||||||
@@ -1349,6 +1422,11 @@ packages:
|
|||||||
function-bind@1.1.2:
|
function-bind@1.1.2:
|
||||||
resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}
|
resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}
|
||||||
|
|
||||||
|
gauge@3.0.2:
|
||||||
|
resolution: {integrity: sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==}
|
||||||
|
engines: {node: '>=10'}
|
||||||
|
deprecated: This package is no longer supported.
|
||||||
|
|
||||||
get-caller-file@2.0.5:
|
get-caller-file@2.0.5:
|
||||||
resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}
|
resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}
|
||||||
engines: {node: 6.* || 8.* || >= 10.*}
|
engines: {node: 6.* || 8.* || >= 10.*}
|
||||||
@@ -1376,6 +1454,10 @@ packages:
|
|||||||
resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==}
|
resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==}
|
||||||
engines: {node: 18 || 20 || >=22}
|
engines: {node: 18 || 20 || >=22}
|
||||||
|
|
||||||
|
glob@7.2.3:
|
||||||
|
resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}
|
||||||
|
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
|
||||||
|
|
||||||
gopd@1.2.0:
|
gopd@1.2.0:
|
||||||
resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}
|
resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}
|
||||||
engines: {node: '>= 0.4'}
|
engines: {node: '>= 0.4'}
|
||||||
@@ -1388,6 +1470,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==}
|
resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==}
|
||||||
engines: {node: '>= 0.4'}
|
engines: {node: '>= 0.4'}
|
||||||
|
|
||||||
|
has-unicode@2.0.1:
|
||||||
|
resolution: {integrity: sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==}
|
||||||
|
|
||||||
hasown@2.0.2:
|
hasown@2.0.2:
|
||||||
resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==}
|
resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==}
|
||||||
engines: {node: '>= 0.4'}
|
engines: {node: '>= 0.4'}
|
||||||
@@ -1407,6 +1492,10 @@ packages:
|
|||||||
resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}
|
resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}
|
||||||
engines: {node: '>= 0.8'}
|
engines: {node: '>= 0.8'}
|
||||||
|
|
||||||
|
https-proxy-agent@5.0.1:
|
||||||
|
resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==}
|
||||||
|
engines: {node: '>= 6'}
|
||||||
|
|
||||||
iconv-lite@0.7.2:
|
iconv-lite@0.7.2:
|
||||||
resolution: {integrity: sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==}
|
resolution: {integrity: sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==}
|
||||||
engines: {node: '>=0.10.0'}
|
engines: {node: '>=0.10.0'}
|
||||||
@@ -1426,6 +1515,10 @@ packages:
|
|||||||
resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==}
|
resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==}
|
||||||
engines: {node: '>=0.8.19'}
|
engines: {node: '>=0.8.19'}
|
||||||
|
|
||||||
|
inflight@1.0.6:
|
||||||
|
resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==}
|
||||||
|
deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
|
||||||
|
|
||||||
inherits@2.0.4:
|
inherits@2.0.4:
|
||||||
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
|
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
|
||||||
|
|
||||||
@@ -1542,6 +1635,10 @@ packages:
|
|||||||
magicast@0.5.2:
|
magicast@0.5.2:
|
||||||
resolution: {integrity: sha512-E3ZJh4J3S9KfwdjZhe2afj6R9lGIN5Pher1pF39UGrXRqq/VDaGVIGN13BjHd2u8B61hArAGOnso7nBOouW3TQ==}
|
resolution: {integrity: sha512-E3ZJh4J3S9KfwdjZhe2afj6R9lGIN5Pher1pF39UGrXRqq/VDaGVIGN13BjHd2u8B61hArAGOnso7nBOouW3TQ==}
|
||||||
|
|
||||||
|
make-dir@3.1.0:
|
||||||
|
resolution: {integrity: sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==}
|
||||||
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
make-dir@4.0.0:
|
make-dir@4.0.0:
|
||||||
resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}
|
resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}
|
||||||
engines: {node: '>=10'}
|
engines: {node: '>=10'}
|
||||||
@@ -1570,17 +1667,37 @@ packages:
|
|||||||
resolution: {integrity: sha512-+G4CpNBxa5MprY+04MbgOw1v7So6n5JY166pFi9KfYwT78fxScCeSNQSNzp6dpPSW2rONOps6Ocam1wFhCgoVw==}
|
resolution: {integrity: sha512-+G4CpNBxa5MprY+04MbgOw1v7So6n5JY166pFi9KfYwT78fxScCeSNQSNzp6dpPSW2rONOps6Ocam1wFhCgoVw==}
|
||||||
engines: {node: 18 || 20 || >=22}
|
engines: {node: 18 || 20 || >=22}
|
||||||
|
|
||||||
|
minimatch@3.1.2:
|
||||||
|
resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==}
|
||||||
|
|
||||||
minimatch@9.0.5:
|
minimatch@9.0.5:
|
||||||
resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==}
|
resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==}
|
||||||
engines: {node: '>=16 || 14 >=14.17'}
|
engines: {node: '>=16 || 14 >=14.17'}
|
||||||
|
|
||||||
|
minipass@3.3.6:
|
||||||
|
resolution: {integrity: sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==}
|
||||||
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
|
minipass@5.0.0:
|
||||||
|
resolution: {integrity: sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==}
|
||||||
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
minipass@7.1.3:
|
minipass@7.1.3:
|
||||||
resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==}
|
resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==}
|
||||||
engines: {node: '>=16 || 14 >=14.17'}
|
engines: {node: '>=16 || 14 >=14.17'}
|
||||||
|
|
||||||
|
minizlib@2.1.2:
|
||||||
|
resolution: {integrity: sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==}
|
||||||
|
engines: {node: '>= 8'}
|
||||||
|
|
||||||
mkdirp-classic@0.5.3:
|
mkdirp-classic@0.5.3:
|
||||||
resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==}
|
resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==}
|
||||||
|
|
||||||
|
mkdirp@1.0.4:
|
||||||
|
resolution: {integrity: sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==}
|
||||||
|
engines: {node: '>=10'}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
mnemonist@0.40.0:
|
mnemonist@0.40.0:
|
||||||
resolution: {integrity: sha512-kdd8AFNig2AD5Rkih7EPCXhu/iMvwevQFX/uEiGhZyPZi7fHqOoF4V4kHLpCfysxXMgQ4B52kdPMCwARshKvEg==}
|
resolution: {integrity: sha512-kdd8AFNig2AD5Rkih7EPCXhu/iMvwevQFX/uEiGhZyPZi7fHqOoF4V4kHLpCfysxXMgQ4B52kdPMCwARshKvEg==}
|
||||||
|
|
||||||
@@ -1606,9 +1723,30 @@ packages:
|
|||||||
resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==}
|
resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==}
|
||||||
engines: {node: '>= 0.6'}
|
engines: {node: '>= 0.6'}
|
||||||
|
|
||||||
|
node-addon-api@5.1.0:
|
||||||
|
resolution: {integrity: sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA==}
|
||||||
|
|
||||||
node-fetch-native@1.6.7:
|
node-fetch-native@1.6.7:
|
||||||
resolution: {integrity: sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==}
|
resolution: {integrity: sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==}
|
||||||
|
|
||||||
|
node-fetch@2.7.0:
|
||||||
|
resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==}
|
||||||
|
engines: {node: 4.x || >=6.0.0}
|
||||||
|
peerDependencies:
|
||||||
|
encoding: ^0.1.0
|
||||||
|
peerDependenciesMeta:
|
||||||
|
encoding:
|
||||||
|
optional: true
|
||||||
|
|
||||||
|
nopt@5.0.0:
|
||||||
|
resolution: {integrity: sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==}
|
||||||
|
engines: {node: '>=6'}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
|
npmlog@5.0.1:
|
||||||
|
resolution: {integrity: sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==}
|
||||||
|
deprecated: This package is no longer supported.
|
||||||
|
|
||||||
nypm@0.6.5:
|
nypm@0.6.5:
|
||||||
resolution: {integrity: sha512-K6AJy1GMVyfyMXRVB88700BJqNUkByijGJM8kEHpLdcAt+vSQAVfkWWHYzuRXHSY6xA2sNc5RjTj0p9rE2izVQ==}
|
resolution: {integrity: sha512-K6AJy1GMVyfyMXRVB88700BJqNUkByijGJM8kEHpLdcAt+vSQAVfkWWHYzuRXHSY6xA2sNc5RjTj0p9rE2izVQ==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
@@ -1665,6 +1803,10 @@ packages:
|
|||||||
resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
|
resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
|
||||||
engines: {node: '>=8'}
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
|
path-is-absolute@1.0.1:
|
||||||
|
resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==}
|
||||||
|
engines: {node: '>=0.10.0'}
|
||||||
|
|
||||||
path-key@3.1.1:
|
path-key@3.1.1:
|
||||||
resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}
|
resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}
|
||||||
engines: {node: '>=8'}
|
engines: {node: '>=8'}
|
||||||
@@ -1800,6 +1942,11 @@ packages:
|
|||||||
rfdc@1.4.1:
|
rfdc@1.4.1:
|
||||||
resolution: {integrity: sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==}
|
resolution: {integrity: sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==}
|
||||||
|
|
||||||
|
rimraf@3.0.2:
|
||||||
|
resolution: {integrity: sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==}
|
||||||
|
deprecated: Rimraf versions prior to v4 are no longer supported
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
rimraf@6.1.3:
|
rimraf@6.1.3:
|
||||||
resolution: {integrity: sha512-LKg+Cr2ZF61fkcaK1UdkH2yEBBKnYjTyWzTJT6KNPcSPaiT7HSdhtMXQuN5wkTX0Xu72KQ1l8S42rlmexS2hSA==}
|
resolution: {integrity: sha512-LKg+Cr2ZF61fkcaK1UdkH2yEBBKnYjTyWzTJT6KNPcSPaiT7HSdhtMXQuN5wkTX0Xu72KQ1l8S42rlmexS2hSA==}
|
||||||
engines: {node: 20 || >=22}
|
engines: {node: 20 || >=22}
|
||||||
@@ -1837,6 +1984,10 @@ packages:
|
|||||||
secure-json-parse@4.1.0:
|
secure-json-parse@4.1.0:
|
||||||
resolution: {integrity: sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA==}
|
resolution: {integrity: sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA==}
|
||||||
|
|
||||||
|
semver@6.3.1:
|
||||||
|
resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
semver@7.7.4:
|
semver@7.7.4:
|
||||||
resolution: {integrity: sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==}
|
resolution: {integrity: sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==}
|
||||||
engines: {node: '>=10'}
|
engines: {node: '>=10'}
|
||||||
@@ -1850,6 +2001,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==}
|
resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==}
|
||||||
engines: {node: '>= 18'}
|
engines: {node: '>= 18'}
|
||||||
|
|
||||||
|
set-blocking@2.0.0:
|
||||||
|
resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==}
|
||||||
|
|
||||||
set-cookie-parser@2.7.2:
|
set-cookie-parser@2.7.2:
|
||||||
resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==}
|
resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==}
|
||||||
|
|
||||||
@@ -1883,6 +2037,9 @@ packages:
|
|||||||
siginfo@2.0.0:
|
siginfo@2.0.0:
|
||||||
resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
|
resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
|
||||||
|
|
||||||
|
signal-exit@3.0.7:
|
||||||
|
resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==}
|
||||||
|
|
||||||
signal-exit@4.1.0:
|
signal-exit@4.1.0:
|
||||||
resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
|
resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
|
||||||
engines: {node: '>=14'}
|
engines: {node: '>=14'}
|
||||||
@@ -1937,6 +2094,11 @@ packages:
|
|||||||
resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==}
|
resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==}
|
||||||
engines: {node: '>=6'}
|
engines: {node: '>=6'}
|
||||||
|
|
||||||
|
tar@6.2.1:
|
||||||
|
resolution: {integrity: sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==}
|
||||||
|
engines: {node: '>=10'}
|
||||||
|
deprecated: Old versions of tar are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
|
||||||
|
|
||||||
thread-stream@4.0.0:
|
thread-stream@4.0.0:
|
||||||
resolution: {integrity: sha512-4iMVL6HAINXWf1ZKZjIPcz5wYaOdPhtO8ATvZ+Xqp3BTdaqtAwQkNmKORqcIo5YkQqGXq5cwfswDwMqqQNrpJA==}
|
resolution: {integrity: sha512-4iMVL6HAINXWf1ZKZjIPcz5wYaOdPhtO8ATvZ+Xqp3BTdaqtAwQkNmKORqcIo5YkQqGXq5cwfswDwMqqQNrpJA==}
|
||||||
engines: {node: '>=20'}
|
engines: {node: '>=20'}
|
||||||
@@ -1964,6 +2126,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}
|
resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}
|
||||||
engines: {node: '>=0.6'}
|
engines: {node: '>=0.6'}
|
||||||
|
|
||||||
|
tr46@0.0.3:
|
||||||
|
resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==}
|
||||||
|
|
||||||
ts-api-utils@2.4.0:
|
ts-api-utils@2.4.0:
|
||||||
resolution: {integrity: sha512-3TaVTaAv2gTiMB35i3FiGJaRfwb3Pyn/j3m/bfAvGe8FB7CF6u+LMYqYlDh7reQf7UNvoTvdfAqHGmPGOSsPmA==}
|
resolution: {integrity: sha512-3TaVTaAv2gTiMB35i3FiGJaRfwb3Pyn/j3m/bfAvGe8FB7CF6u+LMYqYlDh7reQf7UNvoTvdfAqHGmPGOSsPmA==}
|
||||||
engines: {node: '>=18.12'}
|
engines: {node: '>=18.12'}
|
||||||
@@ -2092,6 +2257,12 @@ packages:
|
|||||||
jsdom:
|
jsdom:
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
|
webidl-conversions@3.0.1:
|
||||||
|
resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}
|
||||||
|
|
||||||
|
whatwg-url@5.0.0:
|
||||||
|
resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}
|
||||||
|
|
||||||
which@2.0.2:
|
which@2.0.2:
|
||||||
resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}
|
resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}
|
||||||
engines: {node: '>= 8'}
|
engines: {node: '>= 8'}
|
||||||
@@ -2102,6 +2273,9 @@ packages:
|
|||||||
engines: {node: '>=8'}
|
engines: {node: '>=8'}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
|
wide-align@1.1.5:
|
||||||
|
resolution: {integrity: sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==}
|
||||||
|
|
||||||
word-wrap@1.2.5:
|
word-wrap@1.2.5:
|
||||||
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
|
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
|
||||||
engines: {node: '>=0.10.0'}
|
engines: {node: '>=0.10.0'}
|
||||||
@@ -2121,6 +2295,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
|
resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
|
||||||
engines: {node: '>=10'}
|
engines: {node: '>=10'}
|
||||||
|
|
||||||
|
yallist@4.0.0:
|
||||||
|
resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==}
|
||||||
|
|
||||||
yargs-parser@21.1.1:
|
yargs-parser@21.1.1:
|
||||||
resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}
|
resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}
|
||||||
engines: {node: '>=12'}
|
engines: {node: '>=12'}
|
||||||
@@ -2483,6 +2660,21 @@ snapshots:
|
|||||||
|
|
||||||
'@lukeed/ms@2.0.2': {}
|
'@lukeed/ms@2.0.2': {}
|
||||||
|
|
||||||
|
'@mapbox/node-pre-gyp@1.0.11':
|
||||||
|
dependencies:
|
||||||
|
detect-libc: 2.1.2
|
||||||
|
https-proxy-agent: 5.0.1
|
||||||
|
make-dir: 3.1.0
|
||||||
|
node-fetch: 2.7.0
|
||||||
|
nopt: 5.0.0
|
||||||
|
npmlog: 5.0.1
|
||||||
|
rimraf: 3.0.2
|
||||||
|
semver: 7.7.4
|
||||||
|
tar: 6.2.1
|
||||||
|
transitivePeerDependencies:
|
||||||
|
- encoding
|
||||||
|
- supports-color
|
||||||
|
|
||||||
'@modelcontextprotocol/sdk@1.26.0(zod@3.25.76)':
|
'@modelcontextprotocol/sdk@1.26.0(zod@3.25.76)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@hono/node-server': 1.19.9(hono@4.12.0)
|
'@hono/node-server': 1.19.9(hono@4.12.0)
|
||||||
@@ -2642,6 +2834,10 @@ snapshots:
|
|||||||
|
|
||||||
'@standard-schema/spec@1.1.0': {}
|
'@standard-schema/spec@1.1.0': {}
|
||||||
|
|
||||||
|
'@types/bcrypt@5.0.2':
|
||||||
|
dependencies:
|
||||||
|
'@types/node': 25.3.0
|
||||||
|
|
||||||
'@types/chai@5.2.3':
|
'@types/chai@5.2.3':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/deep-eql': 4.0.2
|
'@types/deep-eql': 4.0.2
|
||||||
@@ -2824,6 +3020,8 @@ snapshots:
|
|||||||
'@vitest/pretty-format': 4.0.18
|
'@vitest/pretty-format': 4.0.18
|
||||||
tinyrainbow: 3.0.3
|
tinyrainbow: 3.0.3
|
||||||
|
|
||||||
|
abbrev@1.1.1: {}
|
||||||
|
|
||||||
abstract-logging@2.0.1: {}
|
abstract-logging@2.0.1: {}
|
||||||
|
|
||||||
accepts@2.0.0:
|
accepts@2.0.0:
|
||||||
@@ -2837,6 +3035,12 @@ snapshots:
|
|||||||
|
|
||||||
acorn@8.16.0: {}
|
acorn@8.16.0: {}
|
||||||
|
|
||||||
|
agent-base@6.0.2:
|
||||||
|
dependencies:
|
||||||
|
debug: 4.4.3
|
||||||
|
transitivePeerDependencies:
|
||||||
|
- supports-color
|
||||||
|
|
||||||
ajv-formats@3.0.1(ajv@8.18.0):
|
ajv-formats@3.0.1(ajv@8.18.0):
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
ajv: 8.18.0
|
ajv: 8.18.0
|
||||||
@@ -2861,6 +3065,13 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
color-convert: 2.0.1
|
color-convert: 2.0.1
|
||||||
|
|
||||||
|
aproba@2.1.0: {}
|
||||||
|
|
||||||
|
are-we-there-yet@2.0.0:
|
||||||
|
dependencies:
|
||||||
|
delegates: 1.0.0
|
||||||
|
readable-stream: 3.6.2
|
||||||
|
|
||||||
argparse@2.0.1: {}
|
argparse@2.0.1: {}
|
||||||
|
|
||||||
asn1@0.2.6:
|
asn1@0.2.6:
|
||||||
@@ -2892,6 +3103,14 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
tweetnacl: 0.14.5
|
tweetnacl: 0.14.5
|
||||||
|
|
||||||
|
bcrypt@5.1.1:
|
||||||
|
dependencies:
|
||||||
|
'@mapbox/node-pre-gyp': 1.0.11
|
||||||
|
node-addon-api: 5.1.0
|
||||||
|
transitivePeerDependencies:
|
||||||
|
- encoding
|
||||||
|
- supports-color
|
||||||
|
|
||||||
bl@4.1.0:
|
bl@4.1.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
buffer: 5.7.1
|
buffer: 5.7.1
|
||||||
@@ -2912,6 +3131,11 @@ snapshots:
|
|||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
|
brace-expansion@1.1.12:
|
||||||
|
dependencies:
|
||||||
|
balanced-match: 1.0.2
|
||||||
|
concat-map: 0.0.1
|
||||||
|
|
||||||
brace-expansion@2.0.2:
|
brace-expansion@2.0.2:
|
||||||
dependencies:
|
dependencies:
|
||||||
balanced-match: 1.0.2
|
balanced-match: 1.0.2
|
||||||
@@ -2967,6 +3191,8 @@ snapshots:
|
|||||||
|
|
||||||
chownr@1.1.4: {}
|
chownr@1.1.4: {}
|
||||||
|
|
||||||
|
chownr@2.0.0: {}
|
||||||
|
|
||||||
citty@0.1.6:
|
citty@0.1.6:
|
||||||
dependencies:
|
dependencies:
|
||||||
consola: 3.4.2
|
consola: 3.4.2
|
||||||
@@ -2987,12 +3213,18 @@ snapshots:
|
|||||||
|
|
||||||
color-name@1.1.4: {}
|
color-name@1.1.4: {}
|
||||||
|
|
||||||
|
color-support@1.1.3: {}
|
||||||
|
|
||||||
commander@13.1.0: {}
|
commander@13.1.0: {}
|
||||||
|
|
||||||
|
concat-map@0.0.1: {}
|
||||||
|
|
||||||
confbox@0.2.4: {}
|
confbox@0.2.4: {}
|
||||||
|
|
||||||
consola@3.4.2: {}
|
consola@3.4.2: {}
|
||||||
|
|
||||||
|
console-control-strings@1.1.0: {}
|
||||||
|
|
||||||
content-disposition@1.0.1: {}
|
content-disposition@1.0.1: {}
|
||||||
|
|
||||||
content-type@1.0.5: {}
|
content-type@1.0.5: {}
|
||||||
@@ -3030,12 +3262,16 @@ snapshots:
|
|||||||
|
|
||||||
defu@6.1.4: {}
|
defu@6.1.4: {}
|
||||||
|
|
||||||
|
delegates@1.0.0: {}
|
||||||
|
|
||||||
depd@2.0.0: {}
|
depd@2.0.0: {}
|
||||||
|
|
||||||
dequal@2.0.3: {}
|
dequal@2.0.3: {}
|
||||||
|
|
||||||
destr@2.0.5: {}
|
destr@2.0.5: {}
|
||||||
|
|
||||||
|
detect-libc@2.1.2: {}
|
||||||
|
|
||||||
docker-modem@5.0.6:
|
docker-modem@5.0.6:
|
||||||
dependencies:
|
dependencies:
|
||||||
debug: 4.4.3
|
debug: 4.4.3
|
||||||
@@ -3345,11 +3581,29 @@ snapshots:
|
|||||||
|
|
||||||
fs-constants@1.0.0: {}
|
fs-constants@1.0.0: {}
|
||||||
|
|
||||||
|
fs-minipass@2.1.0:
|
||||||
|
dependencies:
|
||||||
|
minipass: 3.3.6
|
||||||
|
|
||||||
|
fs.realpath@1.0.0: {}
|
||||||
|
|
||||||
fsevents@2.3.3:
|
fsevents@2.3.3:
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
function-bind@1.1.2: {}
|
function-bind@1.1.2: {}
|
||||||
|
|
||||||
|
gauge@3.0.2:
|
||||||
|
dependencies:
|
||||||
|
aproba: 2.1.0
|
||||||
|
color-support: 1.1.3
|
||||||
|
console-control-strings: 1.1.0
|
||||||
|
has-unicode: 2.0.1
|
||||||
|
object-assign: 4.1.1
|
||||||
|
signal-exit: 3.0.7
|
||||||
|
string-width: 4.2.3
|
||||||
|
strip-ansi: 6.0.1
|
||||||
|
wide-align: 1.1.5
|
||||||
|
|
||||||
get-caller-file@2.0.5: {}
|
get-caller-file@2.0.5: {}
|
||||||
|
|
||||||
get-intrinsic@1.3.0:
|
get-intrinsic@1.3.0:
|
||||||
@@ -3393,12 +3647,23 @@ snapshots:
|
|||||||
minipass: 7.1.3
|
minipass: 7.1.3
|
||||||
path-scurry: 2.0.2
|
path-scurry: 2.0.2
|
||||||
|
|
||||||
|
glob@7.2.3:
|
||||||
|
dependencies:
|
||||||
|
fs.realpath: 1.0.0
|
||||||
|
inflight: 1.0.6
|
||||||
|
inherits: 2.0.4
|
||||||
|
minimatch: 3.1.2
|
||||||
|
once: 1.4.0
|
||||||
|
path-is-absolute: 1.0.1
|
||||||
|
|
||||||
gopd@1.2.0: {}
|
gopd@1.2.0: {}
|
||||||
|
|
||||||
has-flag@4.0.0: {}
|
has-flag@4.0.0: {}
|
||||||
|
|
||||||
has-symbols@1.1.0: {}
|
has-symbols@1.1.0: {}
|
||||||
|
|
||||||
|
has-unicode@2.0.1: {}
|
||||||
|
|
||||||
hasown@2.0.2:
|
hasown@2.0.2:
|
||||||
dependencies:
|
dependencies:
|
||||||
function-bind: 1.1.2
|
function-bind: 1.1.2
|
||||||
@@ -3417,6 +3682,13 @@ snapshots:
|
|||||||
statuses: 2.0.2
|
statuses: 2.0.2
|
||||||
toidentifier: 1.0.1
|
toidentifier: 1.0.1
|
||||||
|
|
||||||
|
https-proxy-agent@5.0.1:
|
||||||
|
dependencies:
|
||||||
|
agent-base: 6.0.2
|
||||||
|
debug: 4.4.3
|
||||||
|
transitivePeerDependencies:
|
||||||
|
- supports-color
|
||||||
|
|
||||||
iconv-lite@0.7.2:
|
iconv-lite@0.7.2:
|
||||||
dependencies:
|
dependencies:
|
||||||
safer-buffer: 2.1.2
|
safer-buffer: 2.1.2
|
||||||
@@ -3429,6 +3701,11 @@ snapshots:
|
|||||||
|
|
||||||
imurmurhash@0.1.4: {}
|
imurmurhash@0.1.4: {}
|
||||||
|
|
||||||
|
inflight@1.0.6:
|
||||||
|
dependencies:
|
||||||
|
once: 1.4.0
|
||||||
|
wrappy: 1.0.2
|
||||||
|
|
||||||
inherits@2.0.4: {}
|
inherits@2.0.4: {}
|
||||||
|
|
||||||
inquirer@12.11.1(@types/node@25.3.0):
|
inquirer@12.11.1(@types/node@25.3.0):
|
||||||
@@ -3533,6 +3810,10 @@ snapshots:
|
|||||||
'@babel/types': 7.29.0
|
'@babel/types': 7.29.0
|
||||||
source-map-js: 1.2.1
|
source-map-js: 1.2.1
|
||||||
|
|
||||||
|
make-dir@3.1.0:
|
||||||
|
dependencies:
|
||||||
|
semver: 6.3.1
|
||||||
|
|
||||||
make-dir@4.0.0:
|
make-dir@4.0.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
semver: 7.7.4
|
semver: 7.7.4
|
||||||
@@ -3553,14 +3834,31 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
brace-expansion: 5.0.2
|
brace-expansion: 5.0.2
|
||||||
|
|
||||||
|
minimatch@3.1.2:
|
||||||
|
dependencies:
|
||||||
|
brace-expansion: 1.1.12
|
||||||
|
|
||||||
minimatch@9.0.5:
|
minimatch@9.0.5:
|
||||||
dependencies:
|
dependencies:
|
||||||
brace-expansion: 2.0.2
|
brace-expansion: 2.0.2
|
||||||
|
|
||||||
|
minipass@3.3.6:
|
||||||
|
dependencies:
|
||||||
|
yallist: 4.0.0
|
||||||
|
|
||||||
|
minipass@5.0.0: {}
|
||||||
|
|
||||||
minipass@7.1.3: {}
|
minipass@7.1.3: {}
|
||||||
|
|
||||||
|
minizlib@2.1.2:
|
||||||
|
dependencies:
|
||||||
|
minipass: 3.3.6
|
||||||
|
yallist: 4.0.0
|
||||||
|
|
||||||
mkdirp-classic@0.5.3: {}
|
mkdirp-classic@0.5.3: {}
|
||||||
|
|
||||||
|
mkdirp@1.0.4: {}
|
||||||
|
|
||||||
mnemonist@0.40.0:
|
mnemonist@0.40.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
obliterator: 2.0.5
|
obliterator: 2.0.5
|
||||||
@@ -3578,8 +3876,25 @@ snapshots:
|
|||||||
|
|
||||||
negotiator@1.0.0: {}
|
negotiator@1.0.0: {}
|
||||||
|
|
||||||
|
node-addon-api@5.1.0: {}
|
||||||
|
|
||||||
node-fetch-native@1.6.7: {}
|
node-fetch-native@1.6.7: {}
|
||||||
|
|
||||||
|
node-fetch@2.7.0:
|
||||||
|
dependencies:
|
||||||
|
whatwg-url: 5.0.0
|
||||||
|
|
||||||
|
nopt@5.0.0:
|
||||||
|
dependencies:
|
||||||
|
abbrev: 1.1.1
|
||||||
|
|
||||||
|
npmlog@5.0.1:
|
||||||
|
dependencies:
|
||||||
|
are-we-there-yet: 2.0.0
|
||||||
|
console-control-strings: 1.1.0
|
||||||
|
gauge: 3.0.2
|
||||||
|
set-blocking: 2.0.0
|
||||||
|
|
||||||
nypm@0.6.5:
|
nypm@0.6.5:
|
||||||
dependencies:
|
dependencies:
|
||||||
citty: 0.2.1
|
citty: 0.2.1
|
||||||
@@ -3629,6 +3944,8 @@ snapshots:
|
|||||||
|
|
||||||
path-exists@4.0.0: {}
|
path-exists@4.0.0: {}
|
||||||
|
|
||||||
|
path-is-absolute@1.0.1: {}
|
||||||
|
|
||||||
path-key@3.1.1: {}
|
path-key@3.1.1: {}
|
||||||
|
|
||||||
path-scurry@2.0.2:
|
path-scurry@2.0.2:
|
||||||
@@ -3766,6 +4083,10 @@ snapshots:
|
|||||||
|
|
||||||
rfdc@1.4.1: {}
|
rfdc@1.4.1: {}
|
||||||
|
|
||||||
|
rimraf@3.0.2:
|
||||||
|
dependencies:
|
||||||
|
glob: 7.2.3
|
||||||
|
|
||||||
rimraf@6.1.3:
|
rimraf@6.1.3:
|
||||||
dependencies:
|
dependencies:
|
||||||
glob: 13.0.6
|
glob: 13.0.6
|
||||||
@@ -3830,6 +4151,8 @@ snapshots:
|
|||||||
|
|
||||||
secure-json-parse@4.1.0: {}
|
secure-json-parse@4.1.0: {}
|
||||||
|
|
||||||
|
semver@6.3.1: {}
|
||||||
|
|
||||||
semver@7.7.4: {}
|
semver@7.7.4: {}
|
||||||
|
|
||||||
send@1.2.1:
|
send@1.2.1:
|
||||||
@@ -3857,6 +4180,8 @@ snapshots:
|
|||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
|
set-blocking@2.0.0: {}
|
||||||
|
|
||||||
set-cookie-parser@2.7.2: {}
|
set-cookie-parser@2.7.2: {}
|
||||||
|
|
||||||
setprototypeof@1.2.0: {}
|
setprototypeof@1.2.0: {}
|
||||||
@@ -3897,6 +4222,8 @@ snapshots:
|
|||||||
|
|
||||||
siginfo@2.0.0: {}
|
siginfo@2.0.0: {}
|
||||||
|
|
||||||
|
signal-exit@3.0.7: {}
|
||||||
|
|
||||||
signal-exit@4.1.0: {}
|
signal-exit@4.1.0: {}
|
||||||
|
|
||||||
sonic-boom@4.2.1:
|
sonic-boom@4.2.1:
|
||||||
@@ -3956,6 +4283,15 @@ snapshots:
|
|||||||
inherits: 2.0.4
|
inherits: 2.0.4
|
||||||
readable-stream: 3.6.2
|
readable-stream: 3.6.2
|
||||||
|
|
||||||
|
tar@6.2.1:
|
||||||
|
dependencies:
|
||||||
|
chownr: 2.0.0
|
||||||
|
fs-minipass: 2.1.0
|
||||||
|
minipass: 5.0.0
|
||||||
|
minizlib: 2.1.2
|
||||||
|
mkdirp: 1.0.4
|
||||||
|
yallist: 4.0.0
|
||||||
|
|
||||||
thread-stream@4.0.0:
|
thread-stream@4.0.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
real-require: 0.2.0
|
real-require: 0.2.0
|
||||||
@@ -3975,6 +4311,8 @@ snapshots:
|
|||||||
|
|
||||||
toidentifier@1.0.1: {}
|
toidentifier@1.0.1: {}
|
||||||
|
|
||||||
|
tr46@0.0.3: {}
|
||||||
|
|
||||||
ts-api-utils@2.4.0(typescript@5.9.3):
|
ts-api-utils@2.4.0(typescript@5.9.3):
|
||||||
dependencies:
|
dependencies:
|
||||||
typescript: 5.9.3
|
typescript: 5.9.3
|
||||||
@@ -4069,6 +4407,13 @@ snapshots:
|
|||||||
- tsx
|
- tsx
|
||||||
- yaml
|
- yaml
|
||||||
|
|
||||||
|
webidl-conversions@3.0.1: {}
|
||||||
|
|
||||||
|
whatwg-url@5.0.0:
|
||||||
|
dependencies:
|
||||||
|
tr46: 0.0.3
|
||||||
|
webidl-conversions: 3.0.1
|
||||||
|
|
||||||
which@2.0.2:
|
which@2.0.2:
|
||||||
dependencies:
|
dependencies:
|
||||||
isexe: 2.0.0
|
isexe: 2.0.0
|
||||||
@@ -4078,6 +4423,10 @@ snapshots:
|
|||||||
siginfo: 2.0.0
|
siginfo: 2.0.0
|
||||||
stackback: 0.0.2
|
stackback: 0.0.2
|
||||||
|
|
||||||
|
wide-align@1.1.5:
|
||||||
|
dependencies:
|
||||||
|
string-width: 4.2.3
|
||||||
|
|
||||||
word-wrap@1.2.5: {}
|
word-wrap@1.2.5: {}
|
||||||
|
|
||||||
wrap-ansi@6.2.0:
|
wrap-ansi@6.2.0:
|
||||||
@@ -4096,6 +4445,8 @@ snapshots:
|
|||||||
|
|
||||||
y18n@5.0.8: {}
|
y18n@5.0.8: {}
|
||||||
|
|
||||||
|
yallist@4.0.0: {}
|
||||||
|
|
||||||
yargs-parser@21.1.1: {}
|
yargs-parser@21.1.1: {}
|
||||||
|
|
||||||
yargs@17.7.2:
|
yargs@17.7.2:
|
||||||
|
|||||||
30
scripts/build-rpm.sh
Executable file
30
scripts/build-rpm.sh
Executable file
@@ -0,0 +1,30 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||||
|
cd "$PROJECT_ROOT"
|
||||||
|
|
||||||
|
# Load .env if present
|
||||||
|
if [ -f .env ]; then
|
||||||
|
set -a; source .env; set +a
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Ensure tools are on PATH
|
||||||
|
export PATH="$HOME/.npm-global/bin:$HOME/.bun/bin:$HOME/.local/bin:$PATH"
|
||||||
|
|
||||||
|
echo "==> Building TypeScript..."
|
||||||
|
pnpm build
|
||||||
|
|
||||||
|
echo "==> Bundling standalone binary..."
|
||||||
|
mkdir -p dist
|
||||||
|
rm -f dist/mcpctl dist/mcpctl-*.rpm
|
||||||
|
bun build src/cli/src/index.ts --compile --outfile dist/mcpctl
|
||||||
|
|
||||||
|
echo "==> Packaging RPM..."
|
||||||
|
nfpm pkg --packager rpm --target dist/
|
||||||
|
|
||||||
|
RPM_FILE=$(ls dist/mcpctl-*.rpm 2>/dev/null | head -1)
|
||||||
|
echo "==> Built: $RPM_FILE"
|
||||||
|
echo " Size: $(du -h "$RPM_FILE" | cut -f1)"
|
||||||
|
rpm -qpi "$RPM_FILE"
|
||||||
55
scripts/publish-rpm.sh
Executable file
55
scripts/publish-rpm.sh
Executable file
@@ -0,0 +1,55 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||||
|
cd "$PROJECT_ROOT"
|
||||||
|
|
||||||
|
# Load .env if present
|
||||||
|
if [ -f .env ]; then
|
||||||
|
set -a; source .env; set +a
|
||||||
|
fi
|
||||||
|
|
||||||
|
GITEA_URL="${GITEA_URL:-http://10.0.0.194:3012}"
|
||||||
|
GITEA_OWNER="${GITEA_OWNER:-michal}"
|
||||||
|
|
||||||
|
if [ -z "$GITEA_TOKEN" ]; then
|
||||||
|
echo "Error: GITEA_TOKEN not set. Add it to .env or export it."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
RPM_FILE=$(ls dist/mcpctl-*.rpm 2>/dev/null | head -1)
|
||||||
|
if [ -z "$RPM_FILE" ]; then
|
||||||
|
echo "Error: No RPM found in dist/. Run scripts/build-rpm.sh first."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Get version string as it appears in Gitea (e.g. "0.1.0-1")
|
||||||
|
RPM_VERSION=$(rpm -qp --queryformat '%{VERSION}-%{RELEASE}' "$RPM_FILE")
|
||||||
|
|
||||||
|
echo "==> Publishing $RPM_FILE (version $RPM_VERSION) to ${GITEA_URL}..."
|
||||||
|
|
||||||
|
# Check if version already exists and delete it first
|
||||||
|
EXISTING=$(curl -s -o /dev/null -w "%{http_code}" \
|
||||||
|
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||||
|
"${GITEA_URL}/api/v1/packages/${GITEA_OWNER}/rpm/mcpctl/${RPM_VERSION}")
|
||||||
|
|
||||||
|
if [ "$EXISTING" = "200" ]; then
|
||||||
|
echo "==> Version $RPM_VERSION already exists, replacing..."
|
||||||
|
curl -s -o /dev/null -X DELETE \
|
||||||
|
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||||
|
"${GITEA_URL}/api/v1/packages/${GITEA_OWNER}/rpm/mcpctl/${RPM_VERSION}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Upload
|
||||||
|
curl --fail -s -X PUT \
|
||||||
|
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||||
|
--upload-file "$RPM_FILE" \
|
||||||
|
"${GITEA_URL}/api/packages/${GITEA_OWNER}/rpm/upload"
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "==> Published successfully!"
|
||||||
|
echo ""
|
||||||
|
echo "Install with:"
|
||||||
|
echo " sudo dnf config-manager --add-repo ${GITEA_URL}/api/packages/${GITEA_OWNER}/rpm.repo"
|
||||||
|
echo " sudo dnf install mcpctl"
|
||||||
41
scripts/release.sh
Executable file
41
scripts/release.sh
Executable file
@@ -0,0 +1,41 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||||
|
cd "$PROJECT_ROOT"
|
||||||
|
|
||||||
|
# Load .env if present
|
||||||
|
if [ -f .env ]; then
|
||||||
|
set -a; source .env; set +a
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "=== mcpctl release ==="
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Build
|
||||||
|
bash scripts/build-rpm.sh
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Publish
|
||||||
|
bash scripts/publish-rpm.sh
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Install locally
|
||||||
|
echo "==> Installing locally..."
|
||||||
|
RPM_FILE=$(ls dist/mcpctl-*.rpm 2>/dev/null | head -1)
|
||||||
|
sudo rpm -U --force "$RPM_FILE"
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "==> Installed:"
|
||||||
|
mcpctl --version
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
GITEA_URL="${GITEA_URL:-http://10.0.0.194:3012}"
|
||||||
|
GITEA_OWNER="${GITEA_OWNER:-michal}"
|
||||||
|
echo "=== Done! ==="
|
||||||
|
echo "Others can install with:"
|
||||||
|
echo " sudo dnf config-manager --add-repo ${GITEA_URL}/api/packages/${GITEA_OWNER}/rpm.repo"
|
||||||
|
echo " sudo dnf install mcpctl"
|
||||||
98
src/cli/src/api-client.ts
Normal file
98
src/cli/src/api-client.ts
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
import http from 'node:http';
|
||||||
|
|
||||||
|
export interface ApiClientOptions {
|
||||||
|
baseUrl: string;
|
||||||
|
timeout?: number | undefined;
|
||||||
|
token?: string | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiResponse<T = unknown> {
|
||||||
|
status: number;
|
||||||
|
data: T;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ApiError extends Error {
|
||||||
|
constructor(
|
||||||
|
public readonly status: number,
|
||||||
|
public readonly body: string,
|
||||||
|
) {
|
||||||
|
super(`API error ${status}: ${body}`);
|
||||||
|
this.name = 'ApiError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function request<T>(method: string, url: string, timeout: number, body?: unknown, token?: string): Promise<ApiResponse<T>> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const parsed = new URL(url);
|
||||||
|
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||||
|
if (token) {
|
||||||
|
headers['Authorization'] = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
const opts: http.RequestOptions = {
|
||||||
|
hostname: parsed.hostname,
|
||||||
|
port: parsed.port,
|
||||||
|
path: parsed.pathname + parsed.search,
|
||||||
|
method,
|
||||||
|
timeout,
|
||||||
|
headers,
|
||||||
|
};
|
||||||
|
|
||||||
|
const req = http.request(opts, (res) => {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
res.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||||
|
res.on('end', () => {
|
||||||
|
const raw = Buffer.concat(chunks).toString('utf-8');
|
||||||
|
const status = res.statusCode ?? 0;
|
||||||
|
if (status >= 400) {
|
||||||
|
reject(new ApiError(status, raw));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
resolve({ status, data: JSON.parse(raw) as T });
|
||||||
|
} catch {
|
||||||
|
resolve({ status, data: raw as unknown as T });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
req.on('error', reject);
|
||||||
|
req.on('timeout', () => {
|
||||||
|
req.destroy();
|
||||||
|
reject(new Error(`Request to ${url} timed out`));
|
||||||
|
});
|
||||||
|
if (body !== undefined) {
|
||||||
|
req.write(JSON.stringify(body));
|
||||||
|
}
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ApiClient {
|
||||||
|
private baseUrl: string;
|
||||||
|
private timeout: number;
|
||||||
|
private token?: string | undefined;
|
||||||
|
|
||||||
|
constructor(opts: ApiClientOptions) {
|
||||||
|
this.baseUrl = opts.baseUrl.replace(/\/$/, '');
|
||||||
|
this.timeout = opts.timeout ?? 10000;
|
||||||
|
this.token = opts.token;
|
||||||
|
}
|
||||||
|
|
||||||
|
async get<T = unknown>(path: string): Promise<T> {
|
||||||
|
const res = await request<T>('GET', `${this.baseUrl}${path}`, this.timeout, undefined, this.token);
|
||||||
|
return res.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async post<T = unknown>(path: string, body?: unknown): Promise<T> {
|
||||||
|
const res = await request<T>('POST', `${this.baseUrl}${path}`, this.timeout, body, this.token);
|
||||||
|
return res.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async put<T = unknown>(path: string, body?: unknown): Promise<T> {
|
||||||
|
const res = await request<T>('PUT', `${this.baseUrl}${path}`, this.timeout, body, this.token);
|
||||||
|
return res.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete(path: string): Promise<void> {
|
||||||
|
await request('DELETE', `${this.baseUrl}${path}`, this.timeout, undefined, this.token);
|
||||||
|
}
|
||||||
|
}
|
||||||
50
src/cli/src/auth/credentials.ts
Normal file
50
src/cli/src/auth/credentials.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, chmodSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { homedir } from 'node:os';
|
||||||
|
|
||||||
|
export interface StoredCredentials {
|
||||||
|
token: string;
|
||||||
|
mcpdUrl: string;
|
||||||
|
user: string;
|
||||||
|
expiresAt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CredentialsDeps {
|
||||||
|
configDir: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function defaultConfigDir(): string {
|
||||||
|
return join(homedir(), '.mcpctl');
|
||||||
|
}
|
||||||
|
|
||||||
|
function credentialsPath(deps?: Partial<CredentialsDeps>): string {
|
||||||
|
return join(deps?.configDir ?? defaultConfigDir(), 'credentials');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveCredentials(creds: StoredCredentials, deps?: Partial<CredentialsDeps>): void {
|
||||||
|
const dir = deps?.configDir ?? defaultConfigDir();
|
||||||
|
if (!existsSync(dir)) {
|
||||||
|
mkdirSync(dir, { recursive: true });
|
||||||
|
}
|
||||||
|
const path = credentialsPath(deps);
|
||||||
|
writeFileSync(path, JSON.stringify(creds, null, 2) + '\n', 'utf-8');
|
||||||
|
chmodSync(path, 0o600);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadCredentials(deps?: Partial<CredentialsDeps>): StoredCredentials | null {
|
||||||
|
const path = credentialsPath(deps);
|
||||||
|
if (!existsSync(path)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const raw = readFileSync(path, 'utf-8');
|
||||||
|
return JSON.parse(raw) as StoredCredentials;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteCredentials(deps?: Partial<CredentialsDeps>): boolean {
|
||||||
|
const path = credentialsPath(deps);
|
||||||
|
if (!existsSync(path)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
unlinkSync(path);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
2
src/cli/src/auth/index.ts
Normal file
2
src/cli/src/auth/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { saveCredentials, loadCredentials, deleteCredentials } from './credentials.js';
|
||||||
|
export type { StoredCredentials, CredentialsDeps } from './credentials.js';
|
||||||
177
src/cli/src/commands/apply.ts
Normal file
177
src/cli/src/commands/apply.ts
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import yaml from 'js-yaml';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import type { ApiClient } from '../api-client.js';
|
||||||
|
|
||||||
|
const ServerSpecSchema = z.object({
|
||||||
|
name: z.string().min(1),
|
||||||
|
description: z.string().default(''),
|
||||||
|
packageName: z.string().optional(),
|
||||||
|
dockerImage: z.string().optional(),
|
||||||
|
transport: z.enum(['STDIO', 'SSE', 'STREAMABLE_HTTP']).default('STDIO'),
|
||||||
|
repositoryUrl: z.string().url().optional(),
|
||||||
|
externalUrl: z.string().url().optional(),
|
||||||
|
command: z.array(z.string()).optional(),
|
||||||
|
containerPort: z.number().int().min(1).max(65535).optional(),
|
||||||
|
replicas: z.number().int().min(0).max(10).default(1),
|
||||||
|
envTemplate: z.array(z.object({
|
||||||
|
name: z.string(),
|
||||||
|
description: z.string().default(''),
|
||||||
|
isSecret: z.boolean().default(false),
|
||||||
|
})).default([]),
|
||||||
|
});
|
||||||
|
|
||||||
|
const ProfileSpecSchema = z.object({
|
||||||
|
name: z.string().min(1),
|
||||||
|
server: z.string().min(1),
|
||||||
|
permissions: z.array(z.string()).default([]),
|
||||||
|
envOverrides: z.record(z.string()).default({}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const ProjectSpecSchema = z.object({
|
||||||
|
name: z.string().min(1),
|
||||||
|
description: z.string().default(''),
|
||||||
|
profiles: z.array(z.string()).default([]),
|
||||||
|
});
|
||||||
|
|
||||||
|
const ApplyConfigSchema = z.object({
|
||||||
|
servers: z.array(ServerSpecSchema).default([]),
|
||||||
|
profiles: z.array(ProfileSpecSchema).default([]),
|
||||||
|
projects: z.array(ProjectSpecSchema).default([]),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type ApplyConfig = z.infer<typeof ApplyConfigSchema>;
|
||||||
|
|
||||||
|
export interface ApplyCommandDeps {
|
||||||
|
client: ApiClient;
|
||||||
|
log: (...args: unknown[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createApplyCommand(deps: ApplyCommandDeps): Command {
|
||||||
|
const { client, log } = deps;
|
||||||
|
|
||||||
|
return new Command('apply')
|
||||||
|
.description('Apply declarative configuration from a YAML or JSON file')
|
||||||
|
.argument('<file>', 'Path to config file (.yaml, .yml, or .json)')
|
||||||
|
.option('--dry-run', 'Validate and show changes without applying')
|
||||||
|
.action(async (file: string, opts: { dryRun?: boolean }) => {
|
||||||
|
const config = loadConfigFile(file);
|
||||||
|
|
||||||
|
if (opts.dryRun) {
|
||||||
|
log('Dry run - would apply:');
|
||||||
|
if (config.servers.length > 0) log(` ${config.servers.length} server(s)`);
|
||||||
|
if (config.profiles.length > 0) log(` ${config.profiles.length} profile(s)`);
|
||||||
|
if (config.projects.length > 0) log(` ${config.projects.length} project(s)`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await applyConfig(client, config, log);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadConfigFile(path: string): ApplyConfig {
|
||||||
|
const raw = readFileSync(path, 'utf-8');
|
||||||
|
let parsed: unknown;
|
||||||
|
|
||||||
|
if (path.endsWith('.json')) {
|
||||||
|
parsed = JSON.parse(raw);
|
||||||
|
} else {
|
||||||
|
parsed = yaml.load(raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ApplyConfigSchema.parse(parsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function applyConfig(client: ApiClient, config: ApplyConfig, log: (...args: unknown[]) => void): Promise<void> {
|
||||||
|
// Apply servers first (profiles depend on servers)
|
||||||
|
for (const server of config.servers) {
|
||||||
|
try {
|
||||||
|
const existing = await findByName(client, 'servers', server.name);
|
||||||
|
if (existing) {
|
||||||
|
await client.put(`/api/v1/servers/${(existing as { id: string }).id}`, server);
|
||||||
|
log(`Updated server: ${server.name}`);
|
||||||
|
} else {
|
||||||
|
await client.post('/api/v1/servers', server);
|
||||||
|
log(`Created server: ${server.name}`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
log(`Error applying server '${server.name}': ${err instanceof Error ? err.message : err}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply profiles (need server IDs)
|
||||||
|
for (const profile of config.profiles) {
|
||||||
|
try {
|
||||||
|
const server = await findByName(client, 'servers', profile.server);
|
||||||
|
if (!server) {
|
||||||
|
log(`Skipping profile '${profile.name}': server '${profile.server}' not found`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const serverId = (server as { id: string }).id;
|
||||||
|
|
||||||
|
const existing = await findProfile(client, serverId, profile.name);
|
||||||
|
if (existing) {
|
||||||
|
await client.put(`/api/v1/profiles/${(existing as { id: string }).id}`, {
|
||||||
|
permissions: profile.permissions,
|
||||||
|
envOverrides: profile.envOverrides,
|
||||||
|
});
|
||||||
|
log(`Updated profile: ${profile.name} (server: ${profile.server})`);
|
||||||
|
} else {
|
||||||
|
await client.post('/api/v1/profiles', {
|
||||||
|
name: profile.name,
|
||||||
|
serverId,
|
||||||
|
permissions: profile.permissions,
|
||||||
|
envOverrides: profile.envOverrides,
|
||||||
|
});
|
||||||
|
log(`Created profile: ${profile.name} (server: ${profile.server})`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
log(`Error applying profile '${profile.name}': ${err instanceof Error ? err.message : err}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply projects
|
||||||
|
for (const project of config.projects) {
|
||||||
|
try {
|
||||||
|
const existing = await findByName(client, 'projects', project.name);
|
||||||
|
if (existing) {
|
||||||
|
await client.put(`/api/v1/projects/${(existing as { id: string }).id}`, {
|
||||||
|
description: project.description,
|
||||||
|
});
|
||||||
|
log(`Updated project: ${project.name}`);
|
||||||
|
} else {
|
||||||
|
await client.post('/api/v1/projects', {
|
||||||
|
name: project.name,
|
||||||
|
description: project.description,
|
||||||
|
});
|
||||||
|
log(`Created project: ${project.name}`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
log(`Error applying project '${project.name}': ${err instanceof Error ? err.message : err}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function findByName(client: ApiClient, resource: string, name: string): Promise<unknown | null> {
|
||||||
|
try {
|
||||||
|
const items = await client.get<Array<{ name: string }>>(`/api/v1/${resource}`);
|
||||||
|
return items.find((item) => item.name === name) ?? null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function findProfile(client: ApiClient, serverId: string, name: string): Promise<unknown | null> {
|
||||||
|
try {
|
||||||
|
const profiles = await client.get<Array<{ name: string; serverId: string }>>(
|
||||||
|
`/api/v1/profiles?serverId=${serverId}`,
|
||||||
|
);
|
||||||
|
return profiles.find((p) => p.name === name) ?? null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Export for testing
|
||||||
|
export { loadConfigFile, applyConfig };
|
||||||
148
src/cli/src/commands/auth.ts
Normal file
148
src/cli/src/commands/auth.ts
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
import http from 'node:http';
|
||||||
|
import { loadConfig } from '../config/index.js';
|
||||||
|
import type { ConfigLoaderDeps } from '../config/index.js';
|
||||||
|
import { saveCredentials, loadCredentials, deleteCredentials } from '../auth/index.js';
|
||||||
|
import type { CredentialsDeps } from '../auth/index.js';
|
||||||
|
|
||||||
|
export interface PromptDeps {
|
||||||
|
input(message: string): Promise<string>;
|
||||||
|
password(message: string): Promise<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AuthCommandDeps {
|
||||||
|
configDeps: Partial<ConfigLoaderDeps>;
|
||||||
|
credentialsDeps: Partial<CredentialsDeps>;
|
||||||
|
prompt: PromptDeps;
|
||||||
|
log: (...args: string[]) => void;
|
||||||
|
loginRequest: (mcpdUrl: string, email: string, password: string) => Promise<LoginResponse>;
|
||||||
|
logoutRequest: (mcpdUrl: string, token: string) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LoginResponse {
|
||||||
|
token: string;
|
||||||
|
user: { email: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
function defaultLoginRequest(mcpdUrl: string, email: string, password: string): Promise<LoginResponse> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const url = new URL('/api/v1/auth/login', mcpdUrl);
|
||||||
|
const body = JSON.stringify({ email, password });
|
||||||
|
const opts: http.RequestOptions = {
|
||||||
|
hostname: url.hostname,
|
||||||
|
port: url.port,
|
||||||
|
path: url.pathname,
|
||||||
|
method: 'POST',
|
||||||
|
timeout: 10000,
|
||||||
|
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
|
||||||
|
};
|
||||||
|
const req = http.request(opts, (res) => {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
res.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||||
|
res.on('end', () => {
|
||||||
|
const raw = Buffer.concat(chunks).toString('utf-8');
|
||||||
|
if (res.statusCode === 401) {
|
||||||
|
reject(new Error('Invalid credentials'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((res.statusCode ?? 0) >= 400) {
|
||||||
|
reject(new Error(`Login failed (${res.statusCode}): ${raw}`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
resolve(JSON.parse(raw) as LoginResponse);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
req.on('error', (err) => reject(new Error(`Cannot reach mcpd: ${err.message}`)));
|
||||||
|
req.on('timeout', () => { req.destroy(); reject(new Error('Login request timed out')); });
|
||||||
|
req.write(body);
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function defaultLogoutRequest(mcpdUrl: string, token: string): Promise<void> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const url = new URL('/api/v1/auth/logout', mcpdUrl);
|
||||||
|
const opts: http.RequestOptions = {
|
||||||
|
hostname: url.hostname,
|
||||||
|
port: url.port,
|
||||||
|
path: url.pathname,
|
||||||
|
method: 'POST',
|
||||||
|
timeout: 10000,
|
||||||
|
headers: { 'Authorization': `Bearer ${token}` },
|
||||||
|
};
|
||||||
|
const req = http.request(opts, (res) => {
|
||||||
|
res.resume();
|
||||||
|
res.on('end', () => resolve());
|
||||||
|
});
|
||||||
|
req.on('error', () => resolve()); // Don't fail logout on network errors
|
||||||
|
req.on('timeout', () => { req.destroy(); resolve(); });
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function defaultInput(message: string): Promise<string> {
|
||||||
|
const { default: inquirer } = await import('inquirer');
|
||||||
|
const { answer } = await inquirer.prompt([{ type: 'input', name: 'answer', message }]);
|
||||||
|
return answer as string;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function defaultPassword(message: string): Promise<string> {
|
||||||
|
const { default: inquirer } = await import('inquirer');
|
||||||
|
const { answer } = await inquirer.prompt([{ type: 'password', name: 'answer', message }]);
|
||||||
|
return answer as string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultDeps: AuthCommandDeps = {
|
||||||
|
configDeps: {},
|
||||||
|
credentialsDeps: {},
|
||||||
|
prompt: { input: defaultInput, password: defaultPassword },
|
||||||
|
log: (...args) => console.log(...args),
|
||||||
|
loginRequest: defaultLoginRequest,
|
||||||
|
logoutRequest: defaultLogoutRequest,
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createLoginCommand(deps?: Partial<AuthCommandDeps>): Command {
|
||||||
|
const { configDeps, credentialsDeps, prompt, log, loginRequest } = { ...defaultDeps, ...deps };
|
||||||
|
|
||||||
|
return new Command('login')
|
||||||
|
.description('Authenticate with mcpd')
|
||||||
|
.option('--mcpd-url <url>', 'mcpd URL to authenticate against')
|
||||||
|
.action(async (opts: { mcpdUrl?: string }) => {
|
||||||
|
const config = loadConfig(configDeps);
|
||||||
|
const mcpdUrl = opts.mcpdUrl ?? config.mcpdUrl;
|
||||||
|
|
||||||
|
const email = await prompt.input('Email:');
|
||||||
|
const password = await prompt.password('Password:');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await loginRequest(mcpdUrl, email, password);
|
||||||
|
saveCredentials({
|
||||||
|
token: result.token,
|
||||||
|
mcpdUrl,
|
||||||
|
user: result.user.email,
|
||||||
|
}, credentialsDeps);
|
||||||
|
log(`Logged in as ${result.user.email}`);
|
||||||
|
} catch (err) {
|
||||||
|
log(`Login failed: ${(err as Error).message}`);
|
||||||
|
process.exitCode = 1;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createLogoutCommand(deps?: Partial<AuthCommandDeps>): Command {
|
||||||
|
const { credentialsDeps, log, logoutRequest } = { ...defaultDeps, ...deps };
|
||||||
|
|
||||||
|
return new Command('logout')
|
||||||
|
.description('Log out and remove stored credentials')
|
||||||
|
.action(async () => {
|
||||||
|
const creds = loadCredentials(credentialsDeps);
|
||||||
|
if (!creds) {
|
||||||
|
log('Not logged in');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await logoutRequest(creds.mcpdUrl, creds.token);
|
||||||
|
deleteCredentials(credentialsDeps);
|
||||||
|
log('Logged out successfully');
|
||||||
|
});
|
||||||
|
}
|
||||||
80
src/cli/src/commands/backup.ts
Normal file
80
src/cli/src/commands/backup.ts
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import type { ApiClient } from '../api-client.js';
|
||||||
|
|
||||||
|
export interface BackupDeps {
|
||||||
|
client: ApiClient;
|
||||||
|
log: (...args: unknown[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createBackupCommand(deps: BackupDeps): Command {
|
||||||
|
const cmd = new Command('backup')
|
||||||
|
.description('Backup mcpctl configuration to a JSON file')
|
||||||
|
.option('-o, --output <path>', 'output file path', 'mcpctl-backup.json')
|
||||||
|
.option('-p, --password <password>', 'encrypt sensitive values with password')
|
||||||
|
.option('-r, --resources <types>', 'resource types to backup (comma-separated: servers,profiles,projects)')
|
||||||
|
.action(async (options: { output: string; password?: string; resources?: string }) => {
|
||||||
|
const body: Record<string, unknown> = {};
|
||||||
|
if (options.password) {
|
||||||
|
body.password = options.password;
|
||||||
|
}
|
||||||
|
if (options.resources) {
|
||||||
|
body.resources = options.resources.split(',').map((s) => s.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
const bundle = await deps.client.post('/api/v1/backup', body);
|
||||||
|
fs.writeFileSync(options.output, JSON.stringify(bundle, null, 2), 'utf-8');
|
||||||
|
deps.log(`Backup saved to ${options.output}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
return cmd;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createRestoreCommand(deps: BackupDeps): Command {
|
||||||
|
const cmd = new Command('restore')
|
||||||
|
.description('Restore mcpctl configuration from a backup file')
|
||||||
|
.option('-i, --input <path>', 'backup file path', 'mcpctl-backup.json')
|
||||||
|
.option('-p, --password <password>', 'decryption password for encrypted backups')
|
||||||
|
.option('-c, --conflict <strategy>', 'conflict resolution: skip, overwrite, fail', 'skip')
|
||||||
|
.action(async (options: { input: string; password?: string; conflict: string }) => {
|
||||||
|
if (!fs.existsSync(options.input)) {
|
||||||
|
deps.log(`Error: File not found: ${options.input}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = fs.readFileSync(options.input, 'utf-8');
|
||||||
|
const bundle = JSON.parse(raw) as unknown;
|
||||||
|
|
||||||
|
const body: Record<string, unknown> = {
|
||||||
|
bundle,
|
||||||
|
conflictStrategy: options.conflict,
|
||||||
|
};
|
||||||
|
if (options.password) {
|
||||||
|
body.password = options.password;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await deps.client.post<{
|
||||||
|
serversCreated: number;
|
||||||
|
serversSkipped: number;
|
||||||
|
profilesCreated: number;
|
||||||
|
profilesSkipped: number;
|
||||||
|
projectsCreated: number;
|
||||||
|
projectsSkipped: number;
|
||||||
|
errors: string[];
|
||||||
|
}>('/api/v1/restore', body);
|
||||||
|
|
||||||
|
deps.log('Restore complete:');
|
||||||
|
deps.log(` Servers: ${result.serversCreated} created, ${result.serversSkipped} skipped`);
|
||||||
|
deps.log(` Profiles: ${result.profilesCreated} created, ${result.profilesSkipped} skipped`);
|
||||||
|
deps.log(` Projects: ${result.projectsCreated} created, ${result.projectsSkipped} skipped`);
|
||||||
|
|
||||||
|
if (result.errors.length > 0) {
|
||||||
|
deps.log(` Errors:`);
|
||||||
|
for (const err of result.errors) {
|
||||||
|
deps.log(` - ${err}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return cmd;
|
||||||
|
}
|
||||||
155
src/cli/src/commands/claude.ts
Normal file
155
src/cli/src/commands/claude.ts
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
import { writeFileSync, readFileSync, existsSync } from 'node:fs';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
import type { ApiClient } from '../api-client.js';
|
||||||
|
|
||||||
|
interface McpConfig {
|
||||||
|
mcpServers: Record<string, { command: string; args: string[]; env?: Record<string, string> }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClaudeCommandDeps {
|
||||||
|
client: ApiClient;
|
||||||
|
log: (...args: unknown[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createClaudeCommand(deps: ClaudeCommandDeps): Command {
|
||||||
|
const { client, log } = deps;
|
||||||
|
|
||||||
|
const cmd = new Command('claude')
|
||||||
|
.description('Manage Claude MCP configuration (.mcp.json)');
|
||||||
|
|
||||||
|
cmd
|
||||||
|
.command('generate <projectId>')
|
||||||
|
.description('Generate .mcp.json from a project configuration')
|
||||||
|
.option('-o, --output <path>', 'Output file path', '.mcp.json')
|
||||||
|
.option('--merge', 'Merge with existing .mcp.json instead of overwriting')
|
||||||
|
.option('--stdout', 'Print to stdout instead of writing a file')
|
||||||
|
.action(async (projectId: string, opts: { output: string; merge?: boolean; stdout?: boolean }) => {
|
||||||
|
const config = await client.get<McpConfig>(`/api/v1/projects/${projectId}/mcp-config`);
|
||||||
|
|
||||||
|
if (opts.stdout) {
|
||||||
|
log(JSON.stringify(config, null, 2));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const outputPath = resolve(opts.output);
|
||||||
|
let finalConfig = config;
|
||||||
|
|
||||||
|
if (opts.merge && existsSync(outputPath)) {
|
||||||
|
try {
|
||||||
|
const existing = JSON.parse(readFileSync(outputPath, 'utf-8')) as McpConfig;
|
||||||
|
finalConfig = {
|
||||||
|
mcpServers: {
|
||||||
|
...existing.mcpServers,
|
||||||
|
...config.mcpServers,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
// If existing file is invalid, just overwrite
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
writeFileSync(outputPath, JSON.stringify(finalConfig, null, 2) + '\n');
|
||||||
|
const serverCount = Object.keys(finalConfig.mcpServers).length;
|
||||||
|
log(`Wrote ${outputPath} (${serverCount} server(s))`);
|
||||||
|
});
|
||||||
|
|
||||||
|
cmd
|
||||||
|
.command('show')
|
||||||
|
.description('Show current .mcp.json configuration')
|
||||||
|
.option('-p, --path <path>', 'Path to .mcp.json', '.mcp.json')
|
||||||
|
.action((opts: { path: string }) => {
|
||||||
|
const filePath = resolve(opts.path);
|
||||||
|
if (!existsSync(filePath)) {
|
||||||
|
log(`No .mcp.json found at ${filePath}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const content = readFileSync(filePath, 'utf-8');
|
||||||
|
try {
|
||||||
|
const config = JSON.parse(content) as McpConfig;
|
||||||
|
const servers = Object.entries(config.mcpServers ?? {});
|
||||||
|
if (servers.length === 0) {
|
||||||
|
log('No MCP servers configured.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
log(`MCP servers in ${filePath}:\n`);
|
||||||
|
for (const [name, server] of servers) {
|
||||||
|
log(` ${name}`);
|
||||||
|
log(` command: ${server.command} ${server.args.join(' ')}`);
|
||||||
|
if (server.env) {
|
||||||
|
const envKeys = Object.keys(server.env);
|
||||||
|
log(` env: ${envKeys.join(', ')}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
log(`Invalid JSON in ${filePath}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
cmd
|
||||||
|
.command('add <name>')
|
||||||
|
.description('Add an MCP server entry to .mcp.json')
|
||||||
|
.requiredOption('-c, --command <cmd>', 'Command to run')
|
||||||
|
.option('-a, --args <args...>', 'Command arguments')
|
||||||
|
.option('-e, --env <key=value...>', 'Environment variables')
|
||||||
|
.option('-p, --path <path>', 'Path to .mcp.json', '.mcp.json')
|
||||||
|
.action((name: string, opts: { command: string; args?: string[]; env?: string[]; path: string }) => {
|
||||||
|
const filePath = resolve(opts.path);
|
||||||
|
let config: McpConfig = { mcpServers: {} };
|
||||||
|
|
||||||
|
if (existsSync(filePath)) {
|
||||||
|
try {
|
||||||
|
config = JSON.parse(readFileSync(filePath, 'utf-8')) as McpConfig;
|
||||||
|
} catch {
|
||||||
|
// Start fresh
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const entry: { command: string; args: string[]; env?: Record<string, string> } = {
|
||||||
|
command: opts.command,
|
||||||
|
args: opts.args ?? [],
|
||||||
|
};
|
||||||
|
|
||||||
|
if (opts.env && opts.env.length > 0) {
|
||||||
|
const env: Record<string, string> = {};
|
||||||
|
for (const pair of opts.env) {
|
||||||
|
const eqIdx = pair.indexOf('=');
|
||||||
|
if (eqIdx > 0) {
|
||||||
|
env[pair.slice(0, eqIdx)] = pair.slice(eqIdx + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
entry.env = env;
|
||||||
|
}
|
||||||
|
|
||||||
|
config.mcpServers[name] = entry;
|
||||||
|
writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
|
||||||
|
log(`Added '${name}' to ${filePath}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
cmd
|
||||||
|
.command('remove <name>')
|
||||||
|
.description('Remove an MCP server entry from .mcp.json')
|
||||||
|
.option('-p, --path <path>', 'Path to .mcp.json', '.mcp.json')
|
||||||
|
.action((name: string, opts: { path: string }) => {
|
||||||
|
const filePath = resolve(opts.path);
|
||||||
|
if (!existsSync(filePath)) {
|
||||||
|
log(`No .mcp.json found at ${filePath}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const config = JSON.parse(readFileSync(filePath, 'utf-8')) as McpConfig;
|
||||||
|
if (!(name in config.mcpServers)) {
|
||||||
|
log(`Server '${name}' not found in ${filePath}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
delete config.mcpServers[name];
|
||||||
|
writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
|
||||||
|
log(`Removed '${name}' from ${filePath}`);
|
||||||
|
} catch {
|
||||||
|
log(`Invalid JSON in ${filePath}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return cmd;
|
||||||
|
}
|
||||||
@@ -41,6 +41,9 @@ export function createConfigCommand(deps?: Partial<ConfigCommandDeps>): Command
|
|||||||
updates[key] = parseInt(value, 10);
|
updates[key] = parseInt(value, 10);
|
||||||
} else if (key === 'registries') {
|
} else if (key === 'registries') {
|
||||||
updates[key] = value.split(',').map((s) => s.trim());
|
updates[key] = value.split(',').map((s) => s.trim());
|
||||||
|
} else if (key === 'daemonUrl') {
|
||||||
|
// Backward compat: map daemonUrl to mcplocalUrl
|
||||||
|
updates['mcplocalUrl'] = value;
|
||||||
} else {
|
} else {
|
||||||
updates[key] = value;
|
updates[key] = value;
|
||||||
}
|
}
|
||||||
|
|||||||
114
src/cli/src/commands/create.ts
Normal file
114
src/cli/src/commands/create.ts
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
import type { ApiClient } from '../api-client.js';
|
||||||
|
import { resolveNameOrId } from './shared.js';
|
||||||
|
|
||||||
|
export interface CreateCommandDeps {
|
||||||
|
client: ApiClient;
|
||||||
|
log: (...args: unknown[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function collect(value: string, prev: string[]): string[] {
|
||||||
|
return [...prev, value];
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseEnvTemplate(entries: string[]): Array<{ name: string; description: string; isSecret: boolean }> {
|
||||||
|
return entries.map((entry) => {
|
||||||
|
const parts = entry.split(':');
|
||||||
|
if (parts.length < 2) {
|
||||||
|
throw new Error(`Invalid env-template format '${entry}'. Expected NAME:description[:isSecret]`);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
name: parts[0]!,
|
||||||
|
description: parts[1]!,
|
||||||
|
isSecret: parts[2] === 'true',
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseEnvEntries(entries: string[]): Record<string, string> {
|
||||||
|
const result: Record<string, string> = {};
|
||||||
|
for (const entry of entries) {
|
||||||
|
const eqIdx = entry.indexOf('=');
|
||||||
|
if (eqIdx === -1) {
|
||||||
|
throw new Error(`Invalid env format '${entry}'. Expected KEY=value`);
|
||||||
|
}
|
||||||
|
result[entry.slice(0, eqIdx)] = entry.slice(eqIdx + 1);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createCreateCommand(deps: CreateCommandDeps): Command {
|
||||||
|
const { client, log } = deps;
|
||||||
|
|
||||||
|
const cmd = new Command('create')
|
||||||
|
.description('Create a resource (server, profile, project)');
|
||||||
|
|
||||||
|
// --- create server ---
|
||||||
|
cmd.command('server')
|
||||||
|
.description('Create an MCP server definition')
|
||||||
|
.argument('<name>', 'Server name (lowercase, hyphens allowed)')
|
||||||
|
.option('-d, --description <text>', 'Server description', '')
|
||||||
|
.option('--package-name <name>', 'NPM package name')
|
||||||
|
.option('--docker-image <image>', 'Docker image')
|
||||||
|
.option('--transport <type>', 'Transport type (STDIO, SSE, STREAMABLE_HTTP)', 'STDIO')
|
||||||
|
.option('--repository-url <url>', 'Source repository URL')
|
||||||
|
.option('--external-url <url>', 'External endpoint URL')
|
||||||
|
.option('--command <arg>', 'Command argument (repeat for multiple)', collect, [])
|
||||||
|
.option('--container-port <port>', 'Container port number')
|
||||||
|
.option('--replicas <count>', 'Number of replicas', '1')
|
||||||
|
.option('--env-template <entry>', 'Env template (NAME:description[:isSecret], repeat for multiple)', collect, [])
|
||||||
|
.action(async (name: string, opts) => {
|
||||||
|
const body: Record<string, unknown> = {
|
||||||
|
name,
|
||||||
|
description: opts.description,
|
||||||
|
transport: opts.transport,
|
||||||
|
replicas: parseInt(opts.replicas, 10),
|
||||||
|
};
|
||||||
|
if (opts.packageName) body.packageName = opts.packageName;
|
||||||
|
if (opts.dockerImage) body.dockerImage = opts.dockerImage;
|
||||||
|
if (opts.repositoryUrl) body.repositoryUrl = opts.repositoryUrl;
|
||||||
|
if (opts.externalUrl) body.externalUrl = opts.externalUrl;
|
||||||
|
if (opts.command.length > 0) body.command = opts.command;
|
||||||
|
if (opts.containerPort) body.containerPort = parseInt(opts.containerPort, 10);
|
||||||
|
if (opts.envTemplate.length > 0) body.envTemplate = parseEnvTemplate(opts.envTemplate);
|
||||||
|
|
||||||
|
const server = await client.post<{ id: string; name: string }>('/api/v1/servers', body);
|
||||||
|
log(`server '${server.name}' created (id: ${server.id})`);
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- create profile ---
|
||||||
|
cmd.command('profile')
|
||||||
|
.description('Create a profile for an MCP server')
|
||||||
|
.argument('<name>', 'Profile name')
|
||||||
|
.requiredOption('--server <name-or-id>', 'Server name or ID')
|
||||||
|
.option('--permissions <perm>', 'Permission (repeat for multiple)', collect, [])
|
||||||
|
.option('--env <entry>', 'Environment override KEY=value (repeat for multiple)', collect, [])
|
||||||
|
.action(async (name: string, opts) => {
|
||||||
|
const serverId = await resolveNameOrId(client, 'servers', opts.server);
|
||||||
|
|
||||||
|
const body: Record<string, unknown> = {
|
||||||
|
name,
|
||||||
|
serverId,
|
||||||
|
};
|
||||||
|
if (opts.permissions.length > 0) body.permissions = opts.permissions;
|
||||||
|
if (opts.env.length > 0) body.envOverrides = parseEnvEntries(opts.env);
|
||||||
|
|
||||||
|
const profile = await client.post<{ id: string; name: string }>('/api/v1/profiles', body);
|
||||||
|
log(`profile '${profile.name}' created (id: ${profile.id})`);
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- create project ---
|
||||||
|
cmd.command('project')
|
||||||
|
.description('Create a project')
|
||||||
|
.argument('<name>', 'Project name')
|
||||||
|
.option('-d, --description <text>', 'Project description', '')
|
||||||
|
.action(async (name: string, opts) => {
|
||||||
|
const project = await client.post<{ id: string; name: string }>('/api/v1/projects', {
|
||||||
|
name,
|
||||||
|
description: opts.description,
|
||||||
|
});
|
||||||
|
log(`project '${project.name}' created (id: ${project.id})`);
|
||||||
|
});
|
||||||
|
|
||||||
|
return cmd;
|
||||||
|
}
|
||||||
33
src/cli/src/commands/delete.ts
Normal file
33
src/cli/src/commands/delete.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
import type { ApiClient } from '../api-client.js';
|
||||||
|
import { resolveResource, resolveNameOrId } from './shared.js';
|
||||||
|
|
||||||
|
export interface DeleteCommandDeps {
|
||||||
|
client: ApiClient;
|
||||||
|
log: (...args: unknown[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createDeleteCommand(deps: DeleteCommandDeps): Command {
|
||||||
|
const { client, log } = deps;
|
||||||
|
|
||||||
|
return new Command('delete')
|
||||||
|
.description('Delete a resource (server, instance, profile, project)')
|
||||||
|
.argument('<resource>', 'resource type')
|
||||||
|
.argument('<id>', 'resource ID or name')
|
||||||
|
.action(async (resourceArg: string, idOrName: string) => {
|
||||||
|
const resource = resolveResource(resourceArg);
|
||||||
|
|
||||||
|
// Resolve name → ID for any resource type
|
||||||
|
let id: string;
|
||||||
|
try {
|
||||||
|
id = await resolveNameOrId(client, resource, idOrName);
|
||||||
|
} catch {
|
||||||
|
id = idOrName; // Fall through with original
|
||||||
|
}
|
||||||
|
|
||||||
|
await client.delete(`/api/v1/${resource}/${id}`);
|
||||||
|
|
||||||
|
const singular = resource.replace(/s$/, '');
|
||||||
|
log(`${singular} '${idOrName}' deleted.`);
|
||||||
|
});
|
||||||
|
}
|
||||||
221
src/cli/src/commands/describe.ts
Normal file
221
src/cli/src/commands/describe.ts
Normal file
@@ -0,0 +1,221 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
import { formatJson, formatYaml } from '../formatters/output.js';
|
||||||
|
import { resolveResource, resolveNameOrId } from './shared.js';
|
||||||
|
import type { ApiClient } from '../api-client.js';
|
||||||
|
|
||||||
|
export interface DescribeCommandDeps {
|
||||||
|
client: ApiClient;
|
||||||
|
fetchResource: (resource: string, id: string) => Promise<unknown>;
|
||||||
|
fetchInspect?: (id: string) => Promise<unknown>;
|
||||||
|
log: (...args: string[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function pad(label: string, width = 18): string {
|
||||||
|
return label.padEnd(width);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatServerDetail(server: Record<string, unknown>): string {
|
||||||
|
const lines: string[] = [];
|
||||||
|
lines.push(`=== Server: ${server.name} ===`);
|
||||||
|
lines.push(`${pad('Name:')}${server.name}`);
|
||||||
|
lines.push(`${pad('Transport:')}${server.transport ?? '-'}`);
|
||||||
|
lines.push(`${pad('Replicas:')}${server.replicas ?? 1}`);
|
||||||
|
if (server.dockerImage) lines.push(`${pad('Docker Image:')}${server.dockerImage}`);
|
||||||
|
if (server.packageName) lines.push(`${pad('Package:')}${server.packageName}`);
|
||||||
|
if (server.externalUrl) lines.push(`${pad('External URL:')}${server.externalUrl}`);
|
||||||
|
if (server.repositoryUrl) lines.push(`${pad('Repository:')}${server.repositoryUrl}`);
|
||||||
|
if (server.containerPort) lines.push(`${pad('Container Port:')}${server.containerPort}`);
|
||||||
|
if (server.description) lines.push(`${pad('Description:')}${server.description}`);
|
||||||
|
|
||||||
|
const command = server.command as string[] | null;
|
||||||
|
if (command && command.length > 0) {
|
||||||
|
lines.push('');
|
||||||
|
lines.push('Command:');
|
||||||
|
lines.push(` ${command.join(' ')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const envTemplate = server.envTemplate as Array<{ name: string; description: string; isSecret?: boolean }> | undefined;
|
||||||
|
if (envTemplate && envTemplate.length > 0) {
|
||||||
|
lines.push('');
|
||||||
|
lines.push('Environment Template:');
|
||||||
|
const nameW = Math.max(6, ...envTemplate.map((e) => e.name.length)) + 2;
|
||||||
|
const descW = Math.max(12, ...envTemplate.map((e) => e.description.length)) + 2;
|
||||||
|
lines.push(` ${'NAME'.padEnd(nameW)}${'DESCRIPTION'.padEnd(descW)}SECRET`);
|
||||||
|
for (const env of envTemplate) {
|
||||||
|
lines.push(` ${env.name.padEnd(nameW)}${env.description.padEnd(descW)}${env.isSecret ? 'yes' : 'no'}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lines.push('');
|
||||||
|
lines.push('Metadata:');
|
||||||
|
lines.push(` ${pad('ID:', 12)}${server.id}`);
|
||||||
|
if (server.createdAt) lines.push(` ${pad('Created:', 12)}${server.createdAt}`);
|
||||||
|
if (server.updatedAt) lines.push(` ${pad('Updated:', 12)}${server.updatedAt}`);
|
||||||
|
|
||||||
|
return lines.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatInstanceDetail(instance: Record<string, unknown>, inspect?: Record<string, unknown>): string {
|
||||||
|
const lines: string[] = [];
|
||||||
|
lines.push(`=== Instance: ${instance.id} ===`);
|
||||||
|
lines.push(`${pad('Status:')}${instance.status}`);
|
||||||
|
lines.push(`${pad('Server ID:')}${instance.serverId}`);
|
||||||
|
lines.push(`${pad('Container ID:')}${instance.containerId ?? '-'}`);
|
||||||
|
lines.push(`${pad('Port:')}${instance.port ?? '-'}`);
|
||||||
|
|
||||||
|
const metadata = instance.metadata as Record<string, unknown> | undefined;
|
||||||
|
if (metadata && Object.keys(metadata).length > 0) {
|
||||||
|
lines.push('');
|
||||||
|
lines.push('Metadata:');
|
||||||
|
for (const [key, value] of Object.entries(metadata)) {
|
||||||
|
lines.push(` ${pad(key + ':', 16)}${String(value)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inspect) {
|
||||||
|
lines.push('');
|
||||||
|
lines.push('Container:');
|
||||||
|
for (const [key, value] of Object.entries(inspect)) {
|
||||||
|
if (typeof value === 'object' && value !== null) {
|
||||||
|
lines.push(` ${key}: ${JSON.stringify(value)}`);
|
||||||
|
} else {
|
||||||
|
lines.push(` ${pad(key + ':', 16)}${String(value)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lines.push('');
|
||||||
|
lines.push(` ${pad('ID:', 12)}${instance.id}`);
|
||||||
|
if (instance.createdAt) lines.push(` ${pad('Created:', 12)}${instance.createdAt}`);
|
||||||
|
if (instance.updatedAt) lines.push(` ${pad('Updated:', 12)}${instance.updatedAt}`);
|
||||||
|
|
||||||
|
return lines.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatProfileDetail(profile: Record<string, unknown>): string {
|
||||||
|
const lines: string[] = [];
|
||||||
|
lines.push(`=== Profile: ${profile.name} ===`);
|
||||||
|
lines.push(`${pad('Name:')}${profile.name}`);
|
||||||
|
lines.push(`${pad('Server ID:')}${profile.serverId}`);
|
||||||
|
|
||||||
|
const permissions = profile.permissions as string[] | undefined;
|
||||||
|
if (permissions && permissions.length > 0) {
|
||||||
|
lines.push(`${pad('Permissions:')}${permissions.join(', ')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const envOverrides = profile.envOverrides as Record<string, string> | undefined;
|
||||||
|
if (envOverrides && Object.keys(envOverrides).length > 0) {
|
||||||
|
lines.push('');
|
||||||
|
lines.push('Environment Overrides:');
|
||||||
|
const keyW = Math.max(4, ...Object.keys(envOverrides).map((k) => k.length)) + 2;
|
||||||
|
for (const [key, value] of Object.entries(envOverrides)) {
|
||||||
|
lines.push(` ${key.padEnd(keyW)}${value}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lines.push('');
|
||||||
|
lines.push('Metadata:');
|
||||||
|
lines.push(` ${pad('ID:', 12)}${profile.id}`);
|
||||||
|
if (profile.createdAt) lines.push(` ${pad('Created:', 12)}${profile.createdAt}`);
|
||||||
|
if (profile.updatedAt) lines.push(` ${pad('Updated:', 12)}${profile.updatedAt}`);
|
||||||
|
|
||||||
|
return lines.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatProjectDetail(project: Record<string, unknown>): string {
|
||||||
|
const lines: string[] = [];
|
||||||
|
lines.push(`=== Project: ${project.name} ===`);
|
||||||
|
lines.push(`${pad('Name:')}${project.name}`);
|
||||||
|
if (project.description) lines.push(`${pad('Description:')}${project.description}`);
|
||||||
|
if (project.ownerId) lines.push(`${pad('Owner:')}${project.ownerId}`);
|
||||||
|
|
||||||
|
lines.push('');
|
||||||
|
lines.push('Metadata:');
|
||||||
|
lines.push(` ${pad('ID:', 12)}${project.id}`);
|
||||||
|
if (project.createdAt) lines.push(` ${pad('Created:', 12)}${project.createdAt}`);
|
||||||
|
if (project.updatedAt) lines.push(` ${pad('Updated:', 12)}${project.updatedAt}`);
|
||||||
|
|
||||||
|
return lines.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatGenericDetail(obj: Record<string, unknown>): string {
|
||||||
|
const lines: string[] = [];
|
||||||
|
for (const [key, value] of Object.entries(obj)) {
|
||||||
|
if (value === null || value === undefined) {
|
||||||
|
lines.push(`${pad(key + ':')} -`);
|
||||||
|
} else if (Array.isArray(value)) {
|
||||||
|
if (value.length === 0) {
|
||||||
|
lines.push(`${pad(key + ':')} []`);
|
||||||
|
} else {
|
||||||
|
lines.push(`${key}:`);
|
||||||
|
for (const item of value) {
|
||||||
|
lines.push(` - ${typeof item === 'object' ? JSON.stringify(item) : String(item)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (typeof value === 'object') {
|
||||||
|
lines.push(`${key}:`);
|
||||||
|
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
||||||
|
lines.push(` ${pad(k + ':')}${String(v)}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
lines.push(`${pad(key + ':')}${String(value)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return lines.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createDescribeCommand(deps: DescribeCommandDeps): Command {
|
||||||
|
return new Command('describe')
|
||||||
|
.description('Show detailed information about a resource')
|
||||||
|
.argument('<resource>', 'resource type (server, profile, project, instance)')
|
||||||
|
.argument('<id>', 'resource ID or name')
|
||||||
|
.option('-o, --output <format>', 'output format (detail, json, yaml)', 'detail')
|
||||||
|
.action(async (resourceArg: string, idOrName: string, opts: { output: string }) => {
|
||||||
|
const resource = resolveResource(resourceArg);
|
||||||
|
|
||||||
|
// Resolve name → ID
|
||||||
|
let id: string;
|
||||||
|
try {
|
||||||
|
id = await resolveNameOrId(deps.client, resource, idOrName);
|
||||||
|
} catch {
|
||||||
|
id = idOrName;
|
||||||
|
}
|
||||||
|
|
||||||
|
const item = await deps.fetchResource(resource, id) as Record<string, unknown>;
|
||||||
|
|
||||||
|
// Enrich instances with container inspect data
|
||||||
|
let inspect: Record<string, unknown> | undefined;
|
||||||
|
if (resource === 'instances' && deps.fetchInspect && item.containerId) {
|
||||||
|
try {
|
||||||
|
inspect = await deps.fetchInspect(id) as Record<string, unknown>;
|
||||||
|
item.containerInspect = inspect;
|
||||||
|
} catch {
|
||||||
|
// Container may not be available
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (opts.output === 'json') {
|
||||||
|
deps.log(formatJson(item));
|
||||||
|
} else if (opts.output === 'yaml') {
|
||||||
|
deps.log(formatYaml(item));
|
||||||
|
} else {
|
||||||
|
// Visually clean sectioned output
|
||||||
|
switch (resource) {
|
||||||
|
case 'servers':
|
||||||
|
deps.log(formatServerDetail(item));
|
||||||
|
break;
|
||||||
|
case 'instances':
|
||||||
|
deps.log(formatInstanceDetail(item, inspect));
|
||||||
|
break;
|
||||||
|
case 'profiles':
|
||||||
|
deps.log(formatProfileDetail(item));
|
||||||
|
break;
|
||||||
|
case 'projects':
|
||||||
|
deps.log(formatProjectDetail(item));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
deps.log(formatGenericDetail(item));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
114
src/cli/src/commands/edit.ts
Normal file
114
src/cli/src/commands/edit.ts
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
import { writeFileSync, readFileSync, unlinkSync, mkdtempSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { execSync } from 'node:child_process';
|
||||||
|
import yaml from 'js-yaml';
|
||||||
|
import type { ApiClient } from '../api-client.js';
|
||||||
|
import { resolveResource, resolveNameOrId, stripInternalFields } from './shared.js';
|
||||||
|
|
||||||
|
export interface EditCommandDeps {
|
||||||
|
client: ApiClient;
|
||||||
|
log: (...args: unknown[]) => void;
|
||||||
|
/** Override for testing — return editor binary name. */
|
||||||
|
getEditor?: () => string;
|
||||||
|
/** Override for testing — simulate opening the editor. */
|
||||||
|
openEditor?: (filePath: string, editor: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getEditor(deps: EditCommandDeps): string {
|
||||||
|
if (deps.getEditor) return deps.getEditor();
|
||||||
|
return process.env.VISUAL ?? process.env.EDITOR ?? 'vi';
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEditor(filePath: string, editor: string, deps: EditCommandDeps): void {
|
||||||
|
if (deps.openEditor) {
|
||||||
|
deps.openEditor(filePath, editor);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
execSync(`${editor} "${filePath}"`, { stdio: 'inherit' });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createEditCommand(deps: EditCommandDeps): Command {
|
||||||
|
const { client, log } = deps;
|
||||||
|
|
||||||
|
return new Command('edit')
|
||||||
|
.description('Edit a resource in your default editor (server, profile, project)')
|
||||||
|
.argument('<resource>', 'Resource type (server, profile, project)')
|
||||||
|
.argument('<name-or-id>', 'Resource name or ID')
|
||||||
|
.action(async (resourceArg: string, nameOrId: string) => {
|
||||||
|
const resource = resolveResource(resourceArg);
|
||||||
|
|
||||||
|
// Instances are immutable
|
||||||
|
if (resource === 'instances') {
|
||||||
|
log('Error: instances are immutable and cannot be edited.');
|
||||||
|
log('To change an instance, update the server definition and let reconciliation handle it.');
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const validResources = ['servers', 'profiles', 'projects'];
|
||||||
|
if (!validResources.includes(resource)) {
|
||||||
|
log(`Error: unknown resource type '${resourceArg}'`);
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve name → ID
|
||||||
|
const id = await resolveNameOrId(client, resource, nameOrId);
|
||||||
|
|
||||||
|
// Fetch current state
|
||||||
|
const current = await client.get<Record<string, unknown>>(`/api/v1/${resource}/${id}`);
|
||||||
|
|
||||||
|
// Strip read-only fields for editor
|
||||||
|
const editable = stripInternalFields(current);
|
||||||
|
|
||||||
|
// Serialize to YAML
|
||||||
|
const singular = resource.replace(/s$/, '');
|
||||||
|
const header = `# Editing ${singular}: ${nameOrId}\n# Save and close to apply changes. Clear the file to cancel.\n`;
|
||||||
|
const originalYaml = yaml.dump(editable, { lineWidth: 120, noRefs: true });
|
||||||
|
const content = header + originalYaml;
|
||||||
|
|
||||||
|
// Write to temp file
|
||||||
|
const tmpDir = mkdtempSync(join(tmpdir(), 'mcpctl-edit-'));
|
||||||
|
const tmpFile = join(tmpDir, `${singular}-${nameOrId}.yaml`);
|
||||||
|
writeFileSync(tmpFile, content, 'utf-8');
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Open editor
|
||||||
|
const editor = getEditor(deps);
|
||||||
|
openEditor(tmpFile, editor, deps);
|
||||||
|
|
||||||
|
// Read back
|
||||||
|
const modified = readFileSync(tmpFile, 'utf-8');
|
||||||
|
|
||||||
|
// Strip comments for comparison
|
||||||
|
const modifiedClean = modified
|
||||||
|
.split('\n')
|
||||||
|
.filter((line) => !line.startsWith('#'))
|
||||||
|
.join('\n')
|
||||||
|
.trim();
|
||||||
|
|
||||||
|
if (!modifiedClean) {
|
||||||
|
log('Edit cancelled (empty file).');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (modifiedClean === originalYaml.trim()) {
|
||||||
|
log(`${singular} '${nameOrId}' unchanged.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse and apply
|
||||||
|
const updates = yaml.load(modifiedClean) as Record<string, unknown>;
|
||||||
|
await client.put(`/api/v1/${resource}/${id}`, updates);
|
||||||
|
log(`${singular} '${nameOrId}' updated.`);
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
unlinkSync(tmpFile);
|
||||||
|
} catch {
|
||||||
|
// Ignore cleanup errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
130
src/cli/src/commands/get.ts
Normal file
130
src/cli/src/commands/get.ts
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
import { formatTable } from '../formatters/table.js';
|
||||||
|
import { formatJson, formatYaml } from '../formatters/output.js';
|
||||||
|
import type { Column } from '../formatters/table.js';
|
||||||
|
import { resolveResource, stripInternalFields } from './shared.js';
|
||||||
|
|
||||||
|
export interface GetCommandDeps {
|
||||||
|
fetchResource: (resource: string, id?: string) => Promise<unknown[]>;
|
||||||
|
log: (...args: string[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ServerRow {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
transport: string;
|
||||||
|
packageName: string | null;
|
||||||
|
dockerImage: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ProfileRow {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
serverId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ProjectRow {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
ownerId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface InstanceRow {
|
||||||
|
id: string;
|
||||||
|
serverId: string;
|
||||||
|
status: string;
|
||||||
|
containerId: string | null;
|
||||||
|
port: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const serverColumns: Column<ServerRow>[] = [
|
||||||
|
{ header: 'NAME', key: 'name' },
|
||||||
|
{ header: 'TRANSPORT', key: 'transport', width: 16 },
|
||||||
|
{ header: 'PACKAGE', key: (r) => r.packageName ?? '-' },
|
||||||
|
{ header: 'IMAGE', key: (r) => r.dockerImage ?? '-' },
|
||||||
|
{ header: 'ID', key: 'id' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const profileColumns: Column<ProfileRow>[] = [
|
||||||
|
{ header: 'NAME', key: 'name' },
|
||||||
|
{ header: 'SERVER ID', key: 'serverId' },
|
||||||
|
{ header: 'ID', key: 'id' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const projectColumns: Column<ProjectRow>[] = [
|
||||||
|
{ header: 'NAME', key: 'name' },
|
||||||
|
{ header: 'DESCRIPTION', key: 'description', width: 40 },
|
||||||
|
{ header: 'OWNER', key: 'ownerId' },
|
||||||
|
{ header: 'ID', key: 'id' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const instanceColumns: Column<InstanceRow>[] = [
|
||||||
|
{ header: 'STATUS', key: 'status', width: 10 },
|
||||||
|
{ header: 'SERVER ID', key: 'serverId' },
|
||||||
|
{ header: 'PORT', key: (r) => r.port != null ? String(r.port) : '-', width: 6 },
|
||||||
|
{ header: 'CONTAINER', key: (r) => r.containerId ? r.containerId.slice(0, 12) : '-', width: 14 },
|
||||||
|
{ header: 'ID', key: 'id' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function getColumnsForResource(resource: string): Column<Record<string, unknown>>[] {
|
||||||
|
switch (resource) {
|
||||||
|
case 'servers':
|
||||||
|
return serverColumns as unknown as Column<Record<string, unknown>>[];
|
||||||
|
case 'profiles':
|
||||||
|
return profileColumns as unknown as Column<Record<string, unknown>>[];
|
||||||
|
case 'projects':
|
||||||
|
return projectColumns as unknown as Column<Record<string, unknown>>[];
|
||||||
|
case 'instances':
|
||||||
|
return instanceColumns as unknown as Column<Record<string, unknown>>[];
|
||||||
|
default:
|
||||||
|
return [
|
||||||
|
{ header: 'ID', key: 'id' as keyof Record<string, unknown> },
|
||||||
|
{ header: 'NAME', key: 'name' as keyof Record<string, unknown> },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transform API response items into apply-compatible format.
|
||||||
|
* Strips internal fields and wraps in the resource key.
|
||||||
|
*/
|
||||||
|
function toApplyFormat(resource: string, items: unknown[]): Record<string, unknown[]> {
|
||||||
|
const cleaned = items.map((item) => {
|
||||||
|
const obj = stripInternalFields(item as Record<string, unknown>);
|
||||||
|
// For profiles: convert serverId → server (name) for apply compat
|
||||||
|
// We can't resolve the name here without an API call, so keep serverId
|
||||||
|
// but also remove it's not in the apply schema. Actually profiles use
|
||||||
|
// "server" (name) in apply format but serverId from API. Keep serverId
|
||||||
|
// since it can still be used with apply (the apply command resolves names).
|
||||||
|
return obj;
|
||||||
|
});
|
||||||
|
return { [resource]: cleaned };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createGetCommand(deps: GetCommandDeps): Command {
|
||||||
|
return new Command('get')
|
||||||
|
.description('List resources (servers, profiles, projects, instances)')
|
||||||
|
.argument('<resource>', 'resource type (servers, profiles, projects, instances)')
|
||||||
|
.argument('[id]', 'specific resource ID or name')
|
||||||
|
.option('-o, --output <format>', 'output format (table, json, yaml)', 'table')
|
||||||
|
.action(async (resourceArg: string, id: string | undefined, opts: { output: string }) => {
|
||||||
|
const resource = resolveResource(resourceArg);
|
||||||
|
const items = await deps.fetchResource(resource, id);
|
||||||
|
|
||||||
|
if (opts.output === 'json') {
|
||||||
|
// Apply-compatible JSON wrapped in resource key
|
||||||
|
deps.log(formatJson(toApplyFormat(resource, items)));
|
||||||
|
} else if (opts.output === 'yaml') {
|
||||||
|
// Apply-compatible YAML wrapped in resource key
|
||||||
|
deps.log(formatYaml(toApplyFormat(resource, items)));
|
||||||
|
} else {
|
||||||
|
if (items.length === 0) {
|
||||||
|
deps.log(`No ${resource} found.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const columns = getColumnsForResource(resource);
|
||||||
|
deps.log(formatTable(items as Record<string, unknown>[], columns));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
29
src/cli/src/commands/logs.ts
Normal file
29
src/cli/src/commands/logs.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
import type { ApiClient } from '../api-client.js';
|
||||||
|
|
||||||
|
export interface LogsCommandDeps {
|
||||||
|
client: ApiClient;
|
||||||
|
log: (...args: unknown[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createLogsCommand(deps: LogsCommandDeps): Command {
|
||||||
|
const { client, log } = deps;
|
||||||
|
|
||||||
|
return new Command('logs')
|
||||||
|
.description('Get logs from an MCP server instance')
|
||||||
|
.argument('<instance-id>', 'Instance ID')
|
||||||
|
.option('-t, --tail <lines>', 'Number of lines to show')
|
||||||
|
.action(async (id: string, opts: { tail?: string }) => {
|
||||||
|
let url = `/api/v1/instances/${id}/logs`;
|
||||||
|
if (opts.tail) {
|
||||||
|
url += `?tail=${opts.tail}`;
|
||||||
|
}
|
||||||
|
const logs = await client.get<{ stdout: string; stderr: string }>(url);
|
||||||
|
if (logs.stdout) {
|
||||||
|
log(logs.stdout);
|
||||||
|
}
|
||||||
|
if (logs.stderr) {
|
||||||
|
process.stderr.write(logs.stderr);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
60
src/cli/src/commands/project.ts
Normal file
60
src/cli/src/commands/project.ts
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
import type { ApiClient } from '../api-client.js';
|
||||||
|
|
||||||
|
interface Project {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
ownerId: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Profile {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
serverId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProjectCommandDeps {
|
||||||
|
client: ApiClient;
|
||||||
|
log: (...args: unknown[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createProjectCommand(deps: ProjectCommandDeps): Command {
|
||||||
|
const { client, log } = deps;
|
||||||
|
|
||||||
|
const cmd = new Command('project')
|
||||||
|
.alias('proj')
|
||||||
|
.description('Project-specific actions (create with "create project", list with "get projects")');
|
||||||
|
|
||||||
|
cmd
|
||||||
|
.command('profiles <id>')
|
||||||
|
.description('List profiles assigned to a project')
|
||||||
|
.option('-o, --output <format>', 'Output format (table, json)', 'table')
|
||||||
|
.action(async (id: string, opts: { output: string }) => {
|
||||||
|
const profiles = await client.get<Profile[]>(`/api/v1/projects/${id}/profiles`);
|
||||||
|
if (opts.output === 'json') {
|
||||||
|
log(JSON.stringify(profiles, null, 2));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (profiles.length === 0) {
|
||||||
|
log('No profiles assigned.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
log('ID\tNAME\tSERVER');
|
||||||
|
for (const p of profiles) {
|
||||||
|
log(`${p.id}\t${p.name}\t${p.serverId}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
cmd
|
||||||
|
.command('set-profiles <id>')
|
||||||
|
.description('Set the profiles assigned to a project')
|
||||||
|
.argument('<profileIds...>', 'Profile IDs to assign')
|
||||||
|
.action(async (id: string, profileIds: string[]) => {
|
||||||
|
await client.put(`/api/v1/projects/${id}/profiles`, { profileIds });
|
||||||
|
log(`Set ${profileIds.length} profile(s) for project '${id}'.`);
|
||||||
|
});
|
||||||
|
|
||||||
|
return cmd;
|
||||||
|
}
|
||||||
103
src/cli/src/commands/setup.ts
Normal file
103
src/cli/src/commands/setup.ts
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
import type { ApiClient } from '../api-client.js';
|
||||||
|
|
||||||
|
export interface SetupPromptDeps {
|
||||||
|
input: (message: string) => Promise<string>;
|
||||||
|
password: (message: string) => Promise<string>;
|
||||||
|
select: <T extends string>(message: string, choices: Array<{ name: string; value: T }>) => Promise<T>;
|
||||||
|
confirm: (message: string) => Promise<boolean>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SetupCommandDeps {
|
||||||
|
client: ApiClient;
|
||||||
|
prompt: SetupPromptDeps;
|
||||||
|
log: (...args: unknown[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createSetupCommand(deps: SetupCommandDeps): Command {
|
||||||
|
const { client, prompt, log } = deps;
|
||||||
|
|
||||||
|
return new Command('setup')
|
||||||
|
.description('Interactive wizard for configuring an MCP server')
|
||||||
|
.argument('[server-name]', 'Server name to set up (will prompt if not given)')
|
||||||
|
.action(async (serverName?: string) => {
|
||||||
|
log('MCP Server Setup Wizard\n');
|
||||||
|
|
||||||
|
// Step 1: Server name
|
||||||
|
const name = serverName ?? await prompt.input('Server name (lowercase, hyphens allowed):');
|
||||||
|
if (!name) {
|
||||||
|
log('Setup cancelled.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 2: Transport
|
||||||
|
const transport = await prompt.select('Transport type:', [
|
||||||
|
{ name: 'STDIO (command-line process)', value: 'STDIO' as const },
|
||||||
|
{ name: 'SSE (Server-Sent Events over HTTP)', value: 'SSE' as const },
|
||||||
|
{ name: 'Streamable HTTP', value: 'STREAMABLE_HTTP' as const },
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Step 3: Package or image
|
||||||
|
const packageName = await prompt.input('NPM package name (or leave empty):');
|
||||||
|
const dockerImage = await prompt.input('Docker image (or leave empty):');
|
||||||
|
|
||||||
|
// Step 4: Description
|
||||||
|
const description = await prompt.input('Description:');
|
||||||
|
|
||||||
|
// Step 5: Create the server
|
||||||
|
const serverData: Record<string, unknown> = {
|
||||||
|
name,
|
||||||
|
transport,
|
||||||
|
description,
|
||||||
|
};
|
||||||
|
if (packageName) serverData.packageName = packageName;
|
||||||
|
if (dockerImage) serverData.dockerImage = dockerImage;
|
||||||
|
|
||||||
|
let server: { id: string; name: string };
|
||||||
|
try {
|
||||||
|
server = await client.post<{ id: string; name: string }>('/api/v1/servers', serverData);
|
||||||
|
log(`\nServer '${server.name}' created.`);
|
||||||
|
} catch (err) {
|
||||||
|
log(`\nFailed to create server: ${err instanceof Error ? err.message : err}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 6: Create a profile with env vars
|
||||||
|
const createProfile = await prompt.confirm('Create a profile with environment variables?');
|
||||||
|
if (!createProfile) {
|
||||||
|
log('\nSetup complete!');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const profileName = await prompt.input('Profile name:') || 'default';
|
||||||
|
|
||||||
|
// Collect env vars
|
||||||
|
const envOverrides: Record<string, string> = {};
|
||||||
|
let addMore = true;
|
||||||
|
while (addMore) {
|
||||||
|
const envName = await prompt.input('Environment variable name (empty to finish):');
|
||||||
|
if (!envName) break;
|
||||||
|
|
||||||
|
const isSecret = await prompt.confirm(`Is '${envName}' a secret (e.g., API key)?`);
|
||||||
|
const envValue = isSecret
|
||||||
|
? await prompt.password(`Value for ${envName}:`)
|
||||||
|
: await prompt.input(`Value for ${envName}:`);
|
||||||
|
|
||||||
|
envOverrides[envName] = envValue;
|
||||||
|
addMore = await prompt.confirm('Add another environment variable?');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await client.post('/api/v1/profiles', {
|
||||||
|
name: profileName,
|
||||||
|
serverId: server.id,
|
||||||
|
envOverrides,
|
||||||
|
});
|
||||||
|
log(`Profile '${profileName}' created for server '${name}'.`);
|
||||||
|
} catch (err) {
|
||||||
|
log(`Failed to create profile: ${err instanceof Error ? err.message : err}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
log('\nSetup complete!');
|
||||||
|
});
|
||||||
|
}
|
||||||
42
src/cli/src/commands/shared.ts
Normal file
42
src/cli/src/commands/shared.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import type { ApiClient } from '../api-client.js';
|
||||||
|
|
||||||
|
export const RESOURCE_ALIASES: Record<string, string> = {
|
||||||
|
server: 'servers',
|
||||||
|
srv: 'servers',
|
||||||
|
profile: 'profiles',
|
||||||
|
prof: 'profiles',
|
||||||
|
project: 'projects',
|
||||||
|
proj: 'projects',
|
||||||
|
instance: 'instances',
|
||||||
|
inst: 'instances',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function resolveResource(name: string): string {
|
||||||
|
const lower = name.toLowerCase();
|
||||||
|
return RESOURCE_ALIASES[lower] ?? lower;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve a name-or-ID to an ID. CUIDs pass through; names are looked up. */
|
||||||
|
export async function resolveNameOrId(
|
||||||
|
client: ApiClient,
|
||||||
|
resource: string,
|
||||||
|
nameOrId: string,
|
||||||
|
): Promise<string> {
|
||||||
|
// CUIDs start with 'c' followed by 24+ alphanumeric chars
|
||||||
|
if (/^c[a-z0-9]{24}/.test(nameOrId)) {
|
||||||
|
return nameOrId;
|
||||||
|
}
|
||||||
|
const items = await client.get<Array<{ id: string; name: string }>>(`/api/v1/${resource}`);
|
||||||
|
const match = items.find((item) => item.name === nameOrId);
|
||||||
|
if (match) return match.id;
|
||||||
|
throw new Error(`${resource.replace(/s$/, '')} '${nameOrId}' not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Strip internal/read-only fields from an API response to make it apply-compatible. */
|
||||||
|
export function stripInternalFields(obj: Record<string, unknown>): Record<string, unknown> {
|
||||||
|
const result = { ...obj };
|
||||||
|
for (const key of ['id', 'createdAt', 'updatedAt', 'version', 'ownerId']) {
|
||||||
|
delete result[key];
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -2,16 +2,19 @@ import { Command } from 'commander';
|
|||||||
import http from 'node:http';
|
import http from 'node:http';
|
||||||
import { loadConfig } from '../config/index.js';
|
import { loadConfig } from '../config/index.js';
|
||||||
import type { ConfigLoaderDeps } from '../config/index.js';
|
import type { ConfigLoaderDeps } from '../config/index.js';
|
||||||
|
import { loadCredentials } from '../auth/index.js';
|
||||||
|
import type { CredentialsDeps } from '../auth/index.js';
|
||||||
import { formatJson, formatYaml } from '../formatters/index.js';
|
import { formatJson, formatYaml } from '../formatters/index.js';
|
||||||
import { APP_VERSION } from '@mcpctl/shared';
|
import { APP_VERSION } from '@mcpctl/shared';
|
||||||
|
|
||||||
export interface StatusCommandDeps {
|
export interface StatusCommandDeps {
|
||||||
configDeps: Partial<ConfigLoaderDeps>;
|
configDeps: Partial<ConfigLoaderDeps>;
|
||||||
|
credentialsDeps: Partial<CredentialsDeps>;
|
||||||
log: (...args: string[]) => void;
|
log: (...args: string[]) => void;
|
||||||
checkDaemon: (url: string) => Promise<boolean>;
|
checkHealth: (url: string) => Promise<boolean>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function defaultCheckDaemon(url: string): Promise<boolean> {
|
function defaultCheckHealth(url: string): Promise<boolean> {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
const req = http.get(`${url}/health`, { timeout: 3000 }, (res) => {
|
const req = http.get(`${url}/health`, { timeout: 3000 }, (res) => {
|
||||||
resolve(res.statusCode !== undefined && res.statusCode >= 200 && res.statusCode < 400);
|
resolve(res.statusCode !== undefined && res.statusCode >= 200 && res.statusCode < 400);
|
||||||
@@ -27,24 +30,33 @@ function defaultCheckDaemon(url: string): Promise<boolean> {
|
|||||||
|
|
||||||
const defaultDeps: StatusCommandDeps = {
|
const defaultDeps: StatusCommandDeps = {
|
||||||
configDeps: {},
|
configDeps: {},
|
||||||
|
credentialsDeps: {},
|
||||||
log: (...args) => console.log(...args),
|
log: (...args) => console.log(...args),
|
||||||
checkDaemon: defaultCheckDaemon,
|
checkHealth: defaultCheckHealth,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function createStatusCommand(deps?: Partial<StatusCommandDeps>): Command {
|
export function createStatusCommand(deps?: Partial<StatusCommandDeps>): Command {
|
||||||
const { configDeps, log, checkDaemon } = { ...defaultDeps, ...deps };
|
const { configDeps, credentialsDeps, log, checkHealth } = { ...defaultDeps, ...deps };
|
||||||
|
|
||||||
return new Command('status')
|
return new Command('status')
|
||||||
.description('Show mcpctl status and connectivity')
|
.description('Show mcpctl status and connectivity')
|
||||||
.option('-o, --output <format>', 'output format (table, json, yaml)', 'table')
|
.option('-o, --output <format>', 'output format (table, json, yaml)', 'table')
|
||||||
.action(async (opts: { output: string }) => {
|
.action(async (opts: { output: string }) => {
|
||||||
const config = loadConfig(configDeps);
|
const config = loadConfig(configDeps);
|
||||||
const daemonReachable = await checkDaemon(config.daemonUrl);
|
const creds = loadCredentials(credentialsDeps);
|
||||||
|
|
||||||
|
const [mcplocalReachable, mcpdReachable] = await Promise.all([
|
||||||
|
checkHealth(config.mcplocalUrl),
|
||||||
|
checkHealth(config.mcpdUrl),
|
||||||
|
]);
|
||||||
|
|
||||||
const status = {
|
const status = {
|
||||||
version: APP_VERSION,
|
version: APP_VERSION,
|
||||||
daemonUrl: config.daemonUrl,
|
mcplocalUrl: config.mcplocalUrl,
|
||||||
daemonReachable,
|
mcplocalReachable,
|
||||||
|
mcpdUrl: config.mcpdUrl,
|
||||||
|
mcpdReachable,
|
||||||
|
auth: creds ? { user: creds.user } : null,
|
||||||
registries: config.registries,
|
registries: config.registries,
|
||||||
outputFormat: config.outputFormat,
|
outputFormat: config.outputFormat,
|
||||||
};
|
};
|
||||||
@@ -55,7 +67,9 @@ export function createStatusCommand(deps?: Partial<StatusCommandDeps>): Command
|
|||||||
log(formatYaml(status));
|
log(formatYaml(status));
|
||||||
} else {
|
} else {
|
||||||
log(`mcpctl v${status.version}`);
|
log(`mcpctl v${status.version}`);
|
||||||
log(`Daemon: ${status.daemonUrl} (${daemonReachable ? 'connected' : 'unreachable'})`);
|
log(`mcplocal: ${status.mcplocalUrl} (${mcplocalReachable ? 'connected' : 'unreachable'})`);
|
||||||
|
log(`mcpd: ${status.mcpdUrl} (${mcpdReachable ? 'connected' : 'unreachable'})`);
|
||||||
|
log(`Auth: ${creds ? `logged in as ${creds.user}` : 'not logged in'}`);
|
||||||
log(`Registries: ${status.registries.join(', ')}`);
|
log(`Registries: ${status.registries.join(', ')}`);
|
||||||
log(`Output: ${status.outputFormat}`);
|
log(`Output: ${status.outputFormat}`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
export const McpctlConfigSchema = z.object({
|
export const McpctlConfigSchema = z.object({
|
||||||
/** mcpd daemon endpoint */
|
/** mcplocal daemon endpoint (local LLM pre-processing proxy) */
|
||||||
daemonUrl: z.string().default('http://localhost:3000'),
|
mcplocalUrl: z.string().default('http://localhost:3200'),
|
||||||
|
/** mcpd daemon endpoint (remote instance manager) */
|
||||||
|
mcpdUrl: z.string().default('http://localhost:3100'),
|
||||||
|
/** @deprecated Use mcplocalUrl instead. Kept for backward compatibility. */
|
||||||
|
daemonUrl: z.string().optional(),
|
||||||
/** Active registries for search */
|
/** Active registries for search */
|
||||||
registries: z.array(z.enum(['official', 'glama', 'smithery'])).default(['official', 'glama', 'smithery']),
|
registries: z.array(z.enum(['official', 'glama', 'smithery'])).default(['official', 'glama', 'smithery']),
|
||||||
/** Cache TTL in milliseconds */
|
/** Cache TTL in milliseconds */
|
||||||
@@ -15,6 +19,13 @@ export const McpctlConfigSchema = z.object({
|
|||||||
outputFormat: z.enum(['table', 'json', 'yaml']).default('table'),
|
outputFormat: z.enum(['table', 'json', 'yaml']).default('table'),
|
||||||
/** Smithery API key */
|
/** Smithery API key */
|
||||||
smitheryApiKey: z.string().optional(),
|
smitheryApiKey: z.string().optional(),
|
||||||
|
}).transform((cfg) => {
|
||||||
|
// Backward compatibility: if old daemonUrl is set but mcplocalUrl wasn't explicitly changed,
|
||||||
|
// use daemonUrl as mcplocalUrl
|
||||||
|
if (cfg.daemonUrl && cfg.mcplocalUrl === 'http://localhost:3200') {
|
||||||
|
return { ...cfg, mcplocalUrl: cfg.daemonUrl };
|
||||||
|
}
|
||||||
|
return cfg;
|
||||||
});
|
});
|
||||||
|
|
||||||
export type McpctlConfig = z.infer<typeof McpctlConfigSchema>;
|
export type McpctlConfig = z.infer<typeof McpctlConfigSchema>;
|
||||||
|
|||||||
@@ -3,6 +3,22 @@ import { Command } from 'commander';
|
|||||||
import { APP_NAME, APP_VERSION } from '@mcpctl/shared';
|
import { APP_NAME, APP_VERSION } from '@mcpctl/shared';
|
||||||
import { createConfigCommand } from './commands/config.js';
|
import { createConfigCommand } from './commands/config.js';
|
||||||
import { createStatusCommand } from './commands/status.js';
|
import { createStatusCommand } from './commands/status.js';
|
||||||
|
import { createGetCommand } from './commands/get.js';
|
||||||
|
import { createDescribeCommand } from './commands/describe.js';
|
||||||
|
import { createDeleteCommand } from './commands/delete.js';
|
||||||
|
import { createLogsCommand } from './commands/logs.js';
|
||||||
|
import { createApplyCommand } from './commands/apply.js';
|
||||||
|
import { createCreateCommand } from './commands/create.js';
|
||||||
|
import { createEditCommand } from './commands/edit.js';
|
||||||
|
import { createSetupCommand } from './commands/setup.js';
|
||||||
|
import { createClaudeCommand } from './commands/claude.js';
|
||||||
|
import { createProjectCommand } from './commands/project.js';
|
||||||
|
import { createBackupCommand, createRestoreCommand } from './commands/backup.js';
|
||||||
|
import { createLoginCommand, createLogoutCommand } from './commands/auth.js';
|
||||||
|
import { ApiClient } from './api-client.js';
|
||||||
|
import { loadConfig } from './config/index.js';
|
||||||
|
import { loadCredentials } from './auth/index.js';
|
||||||
|
import { resolveNameOrId } from './commands/shared.js';
|
||||||
|
|
||||||
export function createProgram(): Command {
|
export function createProgram(): Command {
|
||||||
const program = new Command()
|
const program = new Command()
|
||||||
@@ -10,10 +26,136 @@ export function createProgram(): Command {
|
|||||||
.description('Manage MCP servers like kubectl manages containers')
|
.description('Manage MCP servers like kubectl manages containers')
|
||||||
.version(APP_VERSION, '-v, --version')
|
.version(APP_VERSION, '-v, --version')
|
||||||
.option('-o, --output <format>', 'output format (table, json, yaml)', 'table')
|
.option('-o, --output <format>', 'output format (table, json, yaml)', 'table')
|
||||||
.option('--daemon-url <url>', 'mcpd daemon URL');
|
.option('--daemon-url <url>', 'mcplocal daemon URL')
|
||||||
|
.option('--direct', 'bypass mcplocal and connect directly to mcpd');
|
||||||
|
|
||||||
program.addCommand(createConfigCommand());
|
program.addCommand(createConfigCommand());
|
||||||
program.addCommand(createStatusCommand());
|
program.addCommand(createStatusCommand());
|
||||||
|
program.addCommand(createLoginCommand());
|
||||||
|
program.addCommand(createLogoutCommand());
|
||||||
|
|
||||||
|
// Resolve target URL: --direct goes to mcpd, default goes to mcplocal
|
||||||
|
const config = loadConfig();
|
||||||
|
const creds = loadCredentials();
|
||||||
|
const opts = program.opts();
|
||||||
|
let baseUrl: string;
|
||||||
|
if (opts.daemonUrl) {
|
||||||
|
baseUrl = opts.daemonUrl as string;
|
||||||
|
} else if (opts.direct) {
|
||||||
|
baseUrl = config.mcpdUrl;
|
||||||
|
} else {
|
||||||
|
baseUrl = config.mcplocalUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
const client = new ApiClient({ baseUrl, token: creds?.token ?? undefined });
|
||||||
|
|
||||||
|
const fetchResource = async (resource: string, nameOrId?: string): Promise<unknown[]> => {
|
||||||
|
if (nameOrId) {
|
||||||
|
let id: string;
|
||||||
|
try {
|
||||||
|
id = await resolveNameOrId(client, resource, nameOrId);
|
||||||
|
} catch {
|
||||||
|
id = nameOrId;
|
||||||
|
}
|
||||||
|
const item = await client.get(`/api/v1/${resource}/${id}`);
|
||||||
|
return [item];
|
||||||
|
}
|
||||||
|
return client.get<unknown[]>(`/api/v1/${resource}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchSingleResource = async (resource: string, nameOrId: string): Promise<unknown> => {
|
||||||
|
let id: string;
|
||||||
|
try {
|
||||||
|
id = await resolveNameOrId(client, resource, nameOrId);
|
||||||
|
} catch {
|
||||||
|
id = nameOrId;
|
||||||
|
}
|
||||||
|
return client.get(`/api/v1/${resource}/${id}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
program.addCommand(createGetCommand({
|
||||||
|
fetchResource,
|
||||||
|
log: (...args) => console.log(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
program.addCommand(createDescribeCommand({
|
||||||
|
client,
|
||||||
|
fetchResource: fetchSingleResource,
|
||||||
|
fetchInspect: async (id: string) => client.get(`/api/v1/instances/${id}/inspect`),
|
||||||
|
log: (...args) => console.log(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
program.addCommand(createDeleteCommand({
|
||||||
|
client,
|
||||||
|
log: (...args) => console.log(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
program.addCommand(createLogsCommand({
|
||||||
|
client,
|
||||||
|
log: (...args) => console.log(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
program.addCommand(createCreateCommand({
|
||||||
|
client,
|
||||||
|
log: (...args) => console.log(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
program.addCommand(createEditCommand({
|
||||||
|
client,
|
||||||
|
log: (...args) => console.log(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
program.addCommand(createApplyCommand({
|
||||||
|
client,
|
||||||
|
log: (...args) => console.log(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
program.addCommand(createSetupCommand({
|
||||||
|
client,
|
||||||
|
prompt: {
|
||||||
|
async input(message) {
|
||||||
|
const { default: inquirer } = await import('inquirer');
|
||||||
|
const { answer } = await inquirer.prompt([{ type: 'input', name: 'answer', message }]);
|
||||||
|
return answer as string;
|
||||||
|
},
|
||||||
|
async password(message) {
|
||||||
|
const { default: inquirer } = await import('inquirer');
|
||||||
|
const { answer } = await inquirer.prompt([{ type: 'password', name: 'answer', message }]);
|
||||||
|
return answer as string;
|
||||||
|
},
|
||||||
|
async select(message, choices) {
|
||||||
|
const { default: inquirer } = await import('inquirer');
|
||||||
|
const { answer } = await inquirer.prompt([{ type: 'list', name: 'answer', message, choices }]);
|
||||||
|
return answer;
|
||||||
|
},
|
||||||
|
async confirm(message) {
|
||||||
|
const { default: inquirer } = await import('inquirer');
|
||||||
|
const { answer } = await inquirer.prompt([{ type: 'confirm', name: 'answer', message }]);
|
||||||
|
return answer as boolean;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
log: (...args) => console.log(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
program.addCommand(createClaudeCommand({
|
||||||
|
client,
|
||||||
|
log: (...args) => console.log(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
program.addCommand(createProjectCommand({
|
||||||
|
client,
|
||||||
|
log: (...args) => console.log(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
program.addCommand(createBackupCommand({
|
||||||
|
client,
|
||||||
|
log: (...args) => console.log(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
program.addCommand(createRestoreCommand({
|
||||||
|
client,
|
||||||
|
log: (...args) => console.log(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
return program;
|
return program;
|
||||||
}
|
}
|
||||||
|
|||||||
100
src/cli/tests/api-client.test.ts
Normal file
100
src/cli/tests/api-client.test.ts
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||||
|
import http from 'node:http';
|
||||||
|
import { ApiClient, ApiError } from '../src/api-client.js';
|
||||||
|
|
||||||
|
let server: http.Server;
|
||||||
|
let port: number;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
server = http.createServer((req, res) => {
|
||||||
|
if (req.url === '/api/v1/servers' && req.method === 'GET') {
|
||||||
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||||
|
res.end(JSON.stringify([{ id: 'srv-1', name: 'slack' }]));
|
||||||
|
} else if (req.url === '/api/v1/servers/srv-1' && req.method === 'GET') {
|
||||||
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ id: 'srv-1', name: 'slack', transport: 'STDIO' }));
|
||||||
|
} else if (req.url === '/api/v1/servers' && req.method === 'POST') {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
req.on('data', (c: Buffer) => chunks.push(c));
|
||||||
|
req.on('end', () => {
|
||||||
|
const body = JSON.parse(Buffer.concat(chunks).toString());
|
||||||
|
res.writeHead(201, { 'Content-Type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ id: 'srv-new', ...body }));
|
||||||
|
});
|
||||||
|
} else if (req.url === '/api/v1/missing' && req.method === 'GET') {
|
||||||
|
res.writeHead(404, { 'Content-Type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ error: 'Not found' }));
|
||||||
|
} else {
|
||||||
|
res.writeHead(404);
|
||||||
|
res.end();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
server.listen(0, () => {
|
||||||
|
const addr = server.address();
|
||||||
|
if (addr && typeof addr === 'object') {
|
||||||
|
port = addr.port;
|
||||||
|
}
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(() => {
|
||||||
|
server.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ApiClient', () => {
|
||||||
|
it('performs GET request for list', async () => {
|
||||||
|
const client = new ApiClient({ baseUrl: `http://localhost:${port}` });
|
||||||
|
const result = await client.get<Array<{ id: string; name: string }>>('/api/v1/servers');
|
||||||
|
expect(result).toEqual([{ id: 'srv-1', name: 'slack' }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('performs GET request for single item', async () => {
|
||||||
|
const client = new ApiClient({ baseUrl: `http://localhost:${port}` });
|
||||||
|
const result = await client.get<{ id: string; name: string }>('/api/v1/servers/srv-1');
|
||||||
|
expect(result.name).toBe('slack');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('performs POST request', async () => {
|
||||||
|
const client = new ApiClient({ baseUrl: `http://localhost:${port}` });
|
||||||
|
const result = await client.post<{ id: string; name: string }>('/api/v1/servers', { name: 'github' });
|
||||||
|
expect(result.id).toBe('srv-new');
|
||||||
|
expect(result.name).toBe('github');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws ApiError on 404', async () => {
|
||||||
|
const client = new ApiClient({ baseUrl: `http://localhost:${port}` });
|
||||||
|
await expect(client.get('/api/v1/missing')).rejects.toThrow(ApiError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws on connection error', async () => {
|
||||||
|
const client = new ApiClient({ baseUrl: 'http://localhost:1' });
|
||||||
|
await expect(client.get('/anything')).rejects.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends Authorization header when token provided', async () => {
|
||||||
|
// We need a separate server to check the header
|
||||||
|
let receivedAuth = '';
|
||||||
|
const authServer = http.createServer((req, res) => {
|
||||||
|
receivedAuth = req.headers['authorization'] ?? '';
|
||||||
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ ok: true }));
|
||||||
|
});
|
||||||
|
const authPort = await new Promise<number>((resolve) => {
|
||||||
|
authServer.listen(0, () => {
|
||||||
|
const addr = authServer.address();
|
||||||
|
if (addr && typeof addr === 'object') resolve(addr.port);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const client = new ApiClient({ baseUrl: `http://localhost:${authPort}`, token: 'my-token' });
|
||||||
|
await client.get('/test');
|
||||||
|
expect(receivedAuth).toBe('Bearer my-token');
|
||||||
|
} finally {
|
||||||
|
authServer.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
59
src/cli/tests/auth/credentials.test.ts
Normal file
59
src/cli/tests/auth/credentials.test.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||||
|
import { mkdtempSync, rmSync, statSync, existsSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { saveCredentials, loadCredentials, deleteCredentials } from '../../src/auth/index.js';
|
||||||
|
|
||||||
|
let tempDir: string;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tempDir = mkdtempSync(join(tmpdir(), 'mcpctl-auth-test-'));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('saveCredentials', () => {
|
||||||
|
it('saves credentials file', () => {
|
||||||
|
saveCredentials({ token: 'tok123', mcpdUrl: 'http://x:3100', user: 'alice@test.com' }, { configDir: tempDir });
|
||||||
|
expect(existsSync(join(tempDir, 'credentials'))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sets 0600 permissions', () => {
|
||||||
|
saveCredentials({ token: 'tok123', mcpdUrl: 'http://x:3100', user: 'alice@test.com' }, { configDir: tempDir });
|
||||||
|
const stat = statSync(join(tempDir, 'credentials'));
|
||||||
|
expect(stat.mode & 0o777).toBe(0o600);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates config dir if missing', () => {
|
||||||
|
const nested = join(tempDir, 'sub', 'dir');
|
||||||
|
saveCredentials({ token: 'tok', mcpdUrl: 'http://x:3100', user: 'bob' }, { configDir: nested });
|
||||||
|
expect(existsSync(join(nested, 'credentials'))).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('loadCredentials', () => {
|
||||||
|
it('returns null when no credentials file', () => {
|
||||||
|
expect(loadCredentials({ configDir: tempDir })).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('round-trips credentials', () => {
|
||||||
|
const creds = { token: 'tok456', mcpdUrl: 'http://remote:3100', user: 'charlie@test.com', expiresAt: '2099-01-01' };
|
||||||
|
saveCredentials(creds, { configDir: tempDir });
|
||||||
|
const loaded = loadCredentials({ configDir: tempDir });
|
||||||
|
expect(loaded).toEqual(creds);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('deleteCredentials', () => {
|
||||||
|
it('returns false when no credentials file', () => {
|
||||||
|
expect(deleteCredentials({ configDir: tempDir })).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes credentials file', () => {
|
||||||
|
saveCredentials({ token: 'tok', mcpdUrl: 'http://x:3100', user: 'u' }, { configDir: tempDir });
|
||||||
|
expect(deleteCredentials({ configDir: tempDir })).toBe(true);
|
||||||
|
expect(existsSync(join(tempDir, 'credentials'))).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
166
src/cli/tests/commands/apply.test.ts
Normal file
166
src/cli/tests/commands/apply.test.ts
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import { writeFileSync, mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { createApplyCommand } from '../../src/commands/apply.js';
|
||||||
|
import type { ApiClient } from '../../src/api-client.js';
|
||||||
|
|
||||||
|
function mockClient(): ApiClient {
|
||||||
|
return {
|
||||||
|
get: vi.fn(async () => []),
|
||||||
|
post: vi.fn(async () => ({ id: 'new-id', name: 'test' })),
|
||||||
|
put: vi.fn(async () => ({ id: 'existing-id', name: 'test' })),
|
||||||
|
delete: vi.fn(async () => {}),
|
||||||
|
} as unknown as ApiClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('apply command', () => {
|
||||||
|
let client: ReturnType<typeof mockClient>;
|
||||||
|
let output: string[];
|
||||||
|
let tmpDir: string;
|
||||||
|
const log = (...args: unknown[]) => output.push(args.map(String).join(' '));
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
client = mockClient();
|
||||||
|
output = [];
|
||||||
|
tmpDir = mkdtempSync(join(tmpdir(), 'mcpctl-test-'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applies servers from YAML file', async () => {
|
||||||
|
const configPath = join(tmpDir, 'config.yaml');
|
||||||
|
writeFileSync(configPath, `
|
||||||
|
servers:
|
||||||
|
- name: slack
|
||||||
|
description: Slack MCP server
|
||||||
|
transport: STDIO
|
||||||
|
packageName: "@anthropic/slack-mcp"
|
||||||
|
`);
|
||||||
|
|
||||||
|
const cmd = createApplyCommand({ client, log });
|
||||||
|
await cmd.parseAsync([configPath], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.post).toHaveBeenCalledWith('/api/v1/servers', expect.objectContaining({ name: 'slack' }));
|
||||||
|
expect(output.join('\n')).toContain('Created server: slack');
|
||||||
|
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applies servers from JSON file', async () => {
|
||||||
|
const configPath = join(tmpDir, 'config.json');
|
||||||
|
writeFileSync(configPath, JSON.stringify({
|
||||||
|
servers: [{ name: 'github', transport: 'STDIO' }],
|
||||||
|
}));
|
||||||
|
|
||||||
|
const cmd = createApplyCommand({ client, log });
|
||||||
|
await cmd.parseAsync([configPath], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.post).toHaveBeenCalledWith('/api/v1/servers', expect.objectContaining({ name: 'github' }));
|
||||||
|
expect(output.join('\n')).toContain('Created server: github');
|
||||||
|
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('updates existing servers', async () => {
|
||||||
|
vi.mocked(client.get).mockResolvedValue([{ id: 'srv-1', name: 'slack' }]);
|
||||||
|
|
||||||
|
const configPath = join(tmpDir, 'config.yaml');
|
||||||
|
writeFileSync(configPath, `
|
||||||
|
servers:
|
||||||
|
- name: slack
|
||||||
|
description: Updated description
|
||||||
|
transport: STDIO
|
||||||
|
`);
|
||||||
|
|
||||||
|
const cmd = createApplyCommand({ client, log });
|
||||||
|
await cmd.parseAsync([configPath], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.put).toHaveBeenCalledWith('/api/v1/servers/srv-1', expect.objectContaining({ name: 'slack' }));
|
||||||
|
expect(output.join('\n')).toContain('Updated server: slack');
|
||||||
|
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('supports dry-run mode', async () => {
|
||||||
|
const configPath = join(tmpDir, 'config.yaml');
|
||||||
|
writeFileSync(configPath, `
|
||||||
|
servers:
|
||||||
|
- name: test
|
||||||
|
transport: STDIO
|
||||||
|
profiles:
|
||||||
|
- name: default
|
||||||
|
server: test
|
||||||
|
`);
|
||||||
|
|
||||||
|
const cmd = createApplyCommand({ client, log });
|
||||||
|
await cmd.parseAsync([configPath, '--dry-run'], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.post).not.toHaveBeenCalled();
|
||||||
|
expect(output.join('\n')).toContain('Dry run');
|
||||||
|
expect(output.join('\n')).toContain('1 server(s)');
|
||||||
|
expect(output.join('\n')).toContain('1 profile(s)');
|
||||||
|
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applies profiles with server lookup', async () => {
|
||||||
|
vi.mocked(client.get).mockImplementation(async (url: string) => {
|
||||||
|
if (url === '/api/v1/servers') return [{ id: 'srv-1', name: 'slack' }];
|
||||||
|
return [];
|
||||||
|
});
|
||||||
|
|
||||||
|
const configPath = join(tmpDir, 'config.yaml');
|
||||||
|
writeFileSync(configPath, `
|
||||||
|
profiles:
|
||||||
|
- name: default
|
||||||
|
server: slack
|
||||||
|
envOverrides:
|
||||||
|
SLACK_TOKEN: "xoxb-test"
|
||||||
|
`);
|
||||||
|
|
||||||
|
const cmd = createApplyCommand({ client, log });
|
||||||
|
await cmd.parseAsync([configPath], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.post).toHaveBeenCalledWith('/api/v1/profiles', expect.objectContaining({
|
||||||
|
name: 'default',
|
||||||
|
serverId: 'srv-1',
|
||||||
|
envOverrides: { SLACK_TOKEN: 'xoxb-test' },
|
||||||
|
}));
|
||||||
|
expect(output.join('\n')).toContain('Created profile: default');
|
||||||
|
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips profiles when server not found', async () => {
|
||||||
|
const configPath = join(tmpDir, 'config.yaml');
|
||||||
|
writeFileSync(configPath, `
|
||||||
|
profiles:
|
||||||
|
- name: default
|
||||||
|
server: nonexistent
|
||||||
|
`);
|
||||||
|
|
||||||
|
const cmd = createApplyCommand({ client, log });
|
||||||
|
await cmd.parseAsync([configPath], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.post).not.toHaveBeenCalled();
|
||||||
|
expect(output.join('\n')).toContain("Skipping profile 'default'");
|
||||||
|
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applies projects', async () => {
|
||||||
|
const configPath = join(tmpDir, 'config.yaml');
|
||||||
|
writeFileSync(configPath, `
|
||||||
|
projects:
|
||||||
|
- name: my-project
|
||||||
|
description: A test project
|
||||||
|
`);
|
||||||
|
|
||||||
|
const cmd = createApplyCommand({ client, log });
|
||||||
|
await cmd.parseAsync([configPath], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.post).toHaveBeenCalledWith('/api/v1/projects', expect.objectContaining({ name: 'my-project' }));
|
||||||
|
expect(output.join('\n')).toContain('Created project: my-project');
|
||||||
|
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
});
|
||||||
144
src/cli/tests/commands/auth.test.ts
Normal file
144
src/cli/tests/commands/auth.test.ts
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||||
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { createLoginCommand, createLogoutCommand } from '../../src/commands/auth.js';
|
||||||
|
import { saveCredentials, loadCredentials } from '../../src/auth/index.js';
|
||||||
|
import { saveConfig, DEFAULT_CONFIG } from '../../src/config/index.js';
|
||||||
|
|
||||||
|
let tempDir: string;
|
||||||
|
let output: string[];
|
||||||
|
|
||||||
|
function log(...args: string[]) {
|
||||||
|
output.push(args.join(' '));
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tempDir = mkdtempSync(join(tmpdir(), 'mcpctl-auth-cmd-test-'));
|
||||||
|
output = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('login command', () => {
|
||||||
|
it('stores credentials on successful login', async () => {
|
||||||
|
const cmd = createLoginCommand({
|
||||||
|
configDeps: { configDir: tempDir },
|
||||||
|
credentialsDeps: { configDir: tempDir },
|
||||||
|
prompt: {
|
||||||
|
input: async () => 'alice@test.com',
|
||||||
|
password: async () => 'secret123',
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
loginRequest: async (_url, email, _password) => ({
|
||||||
|
token: 'session-token-123',
|
||||||
|
user: { email },
|
||||||
|
}),
|
||||||
|
logoutRequest: async () => {},
|
||||||
|
});
|
||||||
|
await cmd.parseAsync([], { from: 'user' });
|
||||||
|
expect(output[0]).toContain('Logged in as alice@test.com');
|
||||||
|
|
||||||
|
const creds = loadCredentials({ configDir: tempDir });
|
||||||
|
expect(creds).not.toBeNull();
|
||||||
|
expect(creds!.token).toBe('session-token-123');
|
||||||
|
expect(creds!.user).toBe('alice@test.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows error on failed login', async () => {
|
||||||
|
const cmd = createLoginCommand({
|
||||||
|
configDeps: { configDir: tempDir },
|
||||||
|
credentialsDeps: { configDir: tempDir },
|
||||||
|
prompt: {
|
||||||
|
input: async () => 'alice@test.com',
|
||||||
|
password: async () => 'wrong',
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
loginRequest: async () => { throw new Error('Invalid credentials'); },
|
||||||
|
logoutRequest: async () => {},
|
||||||
|
});
|
||||||
|
await cmd.parseAsync([], { from: 'user' });
|
||||||
|
expect(output[0]).toContain('Login failed');
|
||||||
|
expect(output[0]).toContain('Invalid credentials');
|
||||||
|
|
||||||
|
const creds = loadCredentials({ configDir: tempDir });
|
||||||
|
expect(creds).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses mcpdUrl from config', async () => {
|
||||||
|
saveConfig({ ...DEFAULT_CONFIG, mcpdUrl: 'http://custom:3100' }, { configDir: tempDir });
|
||||||
|
let capturedUrl = '';
|
||||||
|
const cmd = createLoginCommand({
|
||||||
|
configDeps: { configDir: tempDir },
|
||||||
|
credentialsDeps: { configDir: tempDir },
|
||||||
|
prompt: {
|
||||||
|
input: async () => 'user@test.com',
|
||||||
|
password: async () => 'pass',
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
loginRequest: async (url, email) => {
|
||||||
|
capturedUrl = url;
|
||||||
|
return { token: 'tok', user: { email } };
|
||||||
|
},
|
||||||
|
logoutRequest: async () => {},
|
||||||
|
});
|
||||||
|
await cmd.parseAsync([], { from: 'user' });
|
||||||
|
expect(capturedUrl).toBe('http://custom:3100');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows --mcpd-url flag override', async () => {
|
||||||
|
let capturedUrl = '';
|
||||||
|
const cmd = createLoginCommand({
|
||||||
|
configDeps: { configDir: tempDir },
|
||||||
|
credentialsDeps: { configDir: tempDir },
|
||||||
|
prompt: {
|
||||||
|
input: async () => 'user@test.com',
|
||||||
|
password: async () => 'pass',
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
loginRequest: async (url, email) => {
|
||||||
|
capturedUrl = url;
|
||||||
|
return { token: 'tok', user: { email } };
|
||||||
|
},
|
||||||
|
logoutRequest: async () => {},
|
||||||
|
});
|
||||||
|
await cmd.parseAsync(['--mcpd-url', 'http://override:3100'], { from: 'user' });
|
||||||
|
expect(capturedUrl).toBe('http://override:3100');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('logout command', () => {
|
||||||
|
it('removes credentials on logout', async () => {
|
||||||
|
saveCredentials({ token: 'tok', mcpdUrl: 'http://x:3100', user: 'alice' }, { configDir: tempDir });
|
||||||
|
let logoutCalled = false;
|
||||||
|
const cmd = createLogoutCommand({
|
||||||
|
configDeps: { configDir: tempDir },
|
||||||
|
credentialsDeps: { configDir: tempDir },
|
||||||
|
prompt: { input: async () => '', password: async () => '' },
|
||||||
|
log,
|
||||||
|
loginRequest: async () => ({ token: '', user: { email: '' } }),
|
||||||
|
logoutRequest: async () => { logoutCalled = true; },
|
||||||
|
});
|
||||||
|
await cmd.parseAsync([], { from: 'user' });
|
||||||
|
expect(output[0]).toContain('Logged out successfully');
|
||||||
|
expect(logoutCalled).toBe(true);
|
||||||
|
|
||||||
|
const creds = loadCredentials({ configDir: tempDir });
|
||||||
|
expect(creds).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows not logged in when no credentials', async () => {
|
||||||
|
const cmd = createLogoutCommand({
|
||||||
|
configDeps: { configDir: tempDir },
|
||||||
|
credentialsDeps: { configDir: tempDir },
|
||||||
|
prompt: { input: async () => '', password: async () => '' },
|
||||||
|
log,
|
||||||
|
loginRequest: async () => ({ token: '', user: { email: '' } }),
|
||||||
|
logoutRequest: async () => {},
|
||||||
|
});
|
||||||
|
await cmd.parseAsync([], { from: 'user' });
|
||||||
|
expect(output[0]).toContain('Not logged in');
|
||||||
|
});
|
||||||
|
});
|
||||||
120
src/cli/tests/commands/backup.test.ts
Normal file
120
src/cli/tests/commands/backup.test.ts
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import { createBackupCommand, createRestoreCommand } from '../../src/commands/backup.js';
|
||||||
|
|
||||||
|
const mockClient = {
|
||||||
|
get: vi.fn(),
|
||||||
|
post: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
|
delete: vi.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const log = vi.fn();
|
||||||
|
|
||||||
|
describe('backup command', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.resetAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
// Clean up any created files
|
||||||
|
try { fs.unlinkSync('test-backup.json'); } catch { /* ignore */ }
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates backup command', () => {
|
||||||
|
const cmd = createBackupCommand({ client: mockClient as never, log });
|
||||||
|
expect(cmd.name()).toBe('backup');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('calls API and writes file', async () => {
|
||||||
|
const bundle = { version: '1', servers: [], profiles: [], projects: [] };
|
||||||
|
mockClient.post.mockResolvedValue(bundle);
|
||||||
|
|
||||||
|
const cmd = createBackupCommand({ client: mockClient as never, log });
|
||||||
|
await cmd.parseAsync(['-o', 'test-backup.json'], { from: 'user' });
|
||||||
|
|
||||||
|
expect(mockClient.post).toHaveBeenCalledWith('/api/v1/backup', {});
|
||||||
|
expect(fs.existsSync('test-backup.json')).toBe(true);
|
||||||
|
expect(log).toHaveBeenCalledWith(expect.stringContaining('test-backup.json'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes password when provided', async () => {
|
||||||
|
mockClient.post.mockResolvedValue({ version: '1', servers: [], profiles: [], projects: [] });
|
||||||
|
|
||||||
|
const cmd = createBackupCommand({ client: mockClient as never, log });
|
||||||
|
await cmd.parseAsync(['-o', 'test-backup.json', '-p', 'secret'], { from: 'user' });
|
||||||
|
|
||||||
|
expect(mockClient.post).toHaveBeenCalledWith('/api/v1/backup', { password: 'secret' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes resource filter', async () => {
|
||||||
|
mockClient.post.mockResolvedValue({ version: '1', servers: [], profiles: [], projects: [] });
|
||||||
|
|
||||||
|
const cmd = createBackupCommand({ client: mockClient as never, log });
|
||||||
|
await cmd.parseAsync(['-o', 'test-backup.json', '-r', 'servers,profiles'], { from: 'user' });
|
||||||
|
|
||||||
|
expect(mockClient.post).toHaveBeenCalledWith('/api/v1/backup', {
|
||||||
|
resources: ['servers', 'profiles'],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('restore command', () => {
|
||||||
|
const testFile = 'test-restore-input.json';
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.resetAllMocks();
|
||||||
|
fs.writeFileSync(testFile, JSON.stringify({
|
||||||
|
version: '1', servers: [], profiles: [], projects: [],
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
try { fs.unlinkSync(testFile); } catch { /* ignore */ }
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates restore command', () => {
|
||||||
|
const cmd = createRestoreCommand({ client: mockClient as never, log });
|
||||||
|
expect(cmd.name()).toBe('restore');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reads file and calls API', async () => {
|
||||||
|
mockClient.post.mockResolvedValue({
|
||||||
|
serversCreated: 1, serversSkipped: 0,
|
||||||
|
profilesCreated: 0, profilesSkipped: 0,
|
||||||
|
projectsCreated: 0, projectsSkipped: 0,
|
||||||
|
errors: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
const cmd = createRestoreCommand({ client: mockClient as never, log });
|
||||||
|
await cmd.parseAsync(['-i', testFile], { from: 'user' });
|
||||||
|
|
||||||
|
expect(mockClient.post).toHaveBeenCalledWith('/api/v1/restore', expect.objectContaining({
|
||||||
|
bundle: expect.objectContaining({ version: '1' }),
|
||||||
|
conflictStrategy: 'skip',
|
||||||
|
}));
|
||||||
|
expect(log).toHaveBeenCalledWith('Restore complete:');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports errors from restore', async () => {
|
||||||
|
mockClient.post.mockResolvedValue({
|
||||||
|
serversCreated: 0, serversSkipped: 0,
|
||||||
|
profilesCreated: 0, profilesSkipped: 0,
|
||||||
|
projectsCreated: 0, projectsSkipped: 0,
|
||||||
|
errors: ['Server "x" already exists'],
|
||||||
|
});
|
||||||
|
|
||||||
|
const cmd = createRestoreCommand({ client: mockClient as never, log });
|
||||||
|
await cmd.parseAsync(['-i', testFile], { from: 'user' });
|
||||||
|
|
||||||
|
expect(log).toHaveBeenCalledWith(expect.stringContaining('Errors'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('logs error for missing file', async () => {
|
||||||
|
const cmd = createRestoreCommand({ client: mockClient as never, log });
|
||||||
|
await cmd.parseAsync(['-i', 'nonexistent.json'], { from: 'user' });
|
||||||
|
|
||||||
|
expect(log).toHaveBeenCalledWith(expect.stringContaining('not found'));
|
||||||
|
expect(mockClient.post).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
158
src/cli/tests/commands/claude.test.ts
Normal file
158
src/cli/tests/commands/claude.test.ts
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import { writeFileSync, readFileSync, mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { createClaudeCommand } from '../../src/commands/claude.js';
|
||||||
|
import type { ApiClient } from '../../src/api-client.js';
|
||||||
|
|
||||||
|
function mockClient(): ApiClient {
|
||||||
|
return {
|
||||||
|
get: vi.fn(async () => ({
|
||||||
|
mcpServers: {
|
||||||
|
'slack--default': { command: 'npx', args: ['-y', '@anthropic/slack-mcp'], env: { WORKSPACE: 'test' } },
|
||||||
|
'github--default': { command: 'npx', args: ['-y', '@anthropic/github-mcp'] },
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
post: vi.fn(async () => ({})),
|
||||||
|
put: vi.fn(async () => ({})),
|
||||||
|
delete: vi.fn(async () => {}),
|
||||||
|
} as unknown as ApiClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('claude command', () => {
|
||||||
|
let client: ReturnType<typeof mockClient>;
|
||||||
|
let output: string[];
|
||||||
|
let tmpDir: string;
|
||||||
|
const log = (...args: unknown[]) => output.push(args.map(String).join(' '));
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
client = mockClient();
|
||||||
|
output = [];
|
||||||
|
tmpDir = mkdtempSync(join(tmpdir(), 'mcpctl-claude-'));
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('generate', () => {
|
||||||
|
it('generates .mcp.json from project config', async () => {
|
||||||
|
const outPath = join(tmpDir, '.mcp.json');
|
||||||
|
const cmd = createClaudeCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['generate', 'proj-1', '-o', outPath], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.get).toHaveBeenCalledWith('/api/v1/projects/proj-1/mcp-config');
|
||||||
|
const written = JSON.parse(readFileSync(outPath, 'utf-8'));
|
||||||
|
expect(written.mcpServers['slack--default']).toBeDefined();
|
||||||
|
expect(output.join('\n')).toContain('2 server(s)');
|
||||||
|
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('prints to stdout with --stdout', async () => {
|
||||||
|
const cmd = createClaudeCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['generate', 'proj-1', '--stdout'], { from: 'user' });
|
||||||
|
|
||||||
|
expect(output[0]).toContain('mcpServers');
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('merges with existing .mcp.json', async () => {
|
||||||
|
const outPath = join(tmpDir, '.mcp.json');
|
||||||
|
writeFileSync(outPath, JSON.stringify({
|
||||||
|
mcpServers: { 'existing--server': { command: 'echo', args: [] } },
|
||||||
|
}));
|
||||||
|
|
||||||
|
const cmd = createClaudeCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['generate', 'proj-1', '-o', outPath, '--merge'], { from: 'user' });
|
||||||
|
|
||||||
|
const written = JSON.parse(readFileSync(outPath, 'utf-8'));
|
||||||
|
expect(written.mcpServers['existing--server']).toBeDefined();
|
||||||
|
expect(written.mcpServers['slack--default']).toBeDefined();
|
||||||
|
expect(output.join('\n')).toContain('3 server(s)');
|
||||||
|
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('show', () => {
|
||||||
|
it('shows servers in .mcp.json', () => {
|
||||||
|
const filePath = join(tmpDir, '.mcp.json');
|
||||||
|
writeFileSync(filePath, JSON.stringify({
|
||||||
|
mcpServers: {
|
||||||
|
'slack': { command: 'npx', args: ['-y', '@anthropic/slack-mcp'], env: { TOKEN: 'x' } },
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const cmd = createClaudeCommand({ client, log });
|
||||||
|
cmd.parseAsync(['show', '-p', filePath], { from: 'user' });
|
||||||
|
|
||||||
|
expect(output.join('\n')).toContain('slack');
|
||||||
|
expect(output.join('\n')).toContain('npx -y @anthropic/slack-mcp');
|
||||||
|
expect(output.join('\n')).toContain('TOKEN');
|
||||||
|
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles missing file', () => {
|
||||||
|
const cmd = createClaudeCommand({ client, log });
|
||||||
|
cmd.parseAsync(['show', '-p', join(tmpDir, 'nonexistent.json')], { from: 'user' });
|
||||||
|
|
||||||
|
expect(output.join('\n')).toContain('No .mcp.json found');
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('add', () => {
|
||||||
|
it('adds a server entry', () => {
|
||||||
|
const filePath = join(tmpDir, '.mcp.json');
|
||||||
|
const cmd = createClaudeCommand({ client, log });
|
||||||
|
cmd.parseAsync(['add', 'my-server', '-c', 'npx', '-a', '-y', 'my-pkg', '-p', filePath], { from: 'user' });
|
||||||
|
|
||||||
|
const written = JSON.parse(readFileSync(filePath, 'utf-8'));
|
||||||
|
expect(written.mcpServers['my-server']).toEqual({
|
||||||
|
command: 'npx',
|
||||||
|
args: ['-y', 'my-pkg'],
|
||||||
|
});
|
||||||
|
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('adds server with env vars', () => {
|
||||||
|
const filePath = join(tmpDir, '.mcp.json');
|
||||||
|
const cmd = createClaudeCommand({ client, log });
|
||||||
|
cmd.parseAsync(['add', 'my-server', '-c', 'node', '-e', 'KEY=val', 'SECRET=abc', '-p', filePath], { from: 'user' });
|
||||||
|
|
||||||
|
const written = JSON.parse(readFileSync(filePath, 'utf-8'));
|
||||||
|
expect(written.mcpServers['my-server'].env).toEqual({ KEY: 'val', SECRET: 'abc' });
|
||||||
|
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('remove', () => {
|
||||||
|
it('removes a server entry', () => {
|
||||||
|
const filePath = join(tmpDir, '.mcp.json');
|
||||||
|
writeFileSync(filePath, JSON.stringify({
|
||||||
|
mcpServers: { 'slack': { command: 'npx', args: [] }, 'github': { command: 'npx', args: [] } },
|
||||||
|
}));
|
||||||
|
|
||||||
|
const cmd = createClaudeCommand({ client, log });
|
||||||
|
cmd.parseAsync(['remove', 'slack', '-p', filePath], { from: 'user' });
|
||||||
|
|
||||||
|
const written = JSON.parse(readFileSync(filePath, 'utf-8'));
|
||||||
|
expect(written.mcpServers['slack']).toBeUndefined();
|
||||||
|
expect(written.mcpServers['github']).toBeDefined();
|
||||||
|
expect(output.join('\n')).toContain("Removed 'slack'");
|
||||||
|
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports when server not found', () => {
|
||||||
|
const filePath = join(tmpDir, '.mcp.json');
|
||||||
|
writeFileSync(filePath, JSON.stringify({ mcpServers: {} }));
|
||||||
|
|
||||||
|
const cmd = createClaudeCommand({ client, log });
|
||||||
|
cmd.parseAsync(['remove', 'nonexistent', '-p', filePath], { from: 'user' });
|
||||||
|
|
||||||
|
expect(output.join('\n')).toContain('not found');
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -34,23 +34,38 @@ describe('config view', () => {
|
|||||||
await cmd.parseAsync(['view'], { from: 'user' });
|
await cmd.parseAsync(['view'], { from: 'user' });
|
||||||
expect(output).toHaveLength(1);
|
expect(output).toHaveLength(1);
|
||||||
const parsed = JSON.parse(output[0]) as Record<string, unknown>;
|
const parsed = JSON.parse(output[0]) as Record<string, unknown>;
|
||||||
expect(parsed['daemonUrl']).toBe('http://localhost:3000');
|
expect(parsed['mcplocalUrl']).toBe('http://localhost:3200');
|
||||||
|
expect(parsed['mcpdUrl']).toBe('http://localhost:3100');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('outputs config as YAML with --output yaml', async () => {
|
it('outputs config as YAML with --output yaml', async () => {
|
||||||
const cmd = makeCommand();
|
const cmd = makeCommand();
|
||||||
await cmd.parseAsync(['view', '-o', 'yaml'], { from: 'user' });
|
await cmd.parseAsync(['view', '-o', 'yaml'], { from: 'user' });
|
||||||
expect(output[0]).toContain('daemonUrl:');
|
expect(output[0]).toContain('mcplocalUrl:');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('config set', () => {
|
describe('config set', () => {
|
||||||
it('sets a string value', async () => {
|
it('sets mcplocalUrl', async () => {
|
||||||
const cmd = makeCommand();
|
const cmd = makeCommand();
|
||||||
await cmd.parseAsync(['set', 'daemonUrl', 'http://new:9000'], { from: 'user' });
|
await cmd.parseAsync(['set', 'mcplocalUrl', 'http://new:9000'], { from: 'user' });
|
||||||
expect(output[0]).toContain('daemonUrl');
|
expect(output[0]).toContain('mcplocalUrl');
|
||||||
const config = loadConfig({ configDir: tempDir });
|
const config = loadConfig({ configDir: tempDir });
|
||||||
expect(config.daemonUrl).toBe('http://new:9000');
|
expect(config.mcplocalUrl).toBe('http://new:9000');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sets mcpdUrl', async () => {
|
||||||
|
const cmd = makeCommand();
|
||||||
|
await cmd.parseAsync(['set', 'mcpdUrl', 'http://remote:3100'], { from: 'user' });
|
||||||
|
const config = loadConfig({ configDir: tempDir });
|
||||||
|
expect(config.mcpdUrl).toBe('http://remote:3100');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('maps daemonUrl to mcplocalUrl for backward compat', async () => {
|
||||||
|
const cmd = makeCommand();
|
||||||
|
await cmd.parseAsync(['set', 'daemonUrl', 'http://legacy:3000'], { from: 'user' });
|
||||||
|
const config = loadConfig({ configDir: tempDir });
|
||||||
|
expect(config.mcplocalUrl).toBe('http://legacy:3000');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('sets cacheTTLMs as integer', async () => {
|
it('sets cacheTTLMs as integer', async () => {
|
||||||
@@ -87,13 +102,13 @@ describe('config path', () => {
|
|||||||
describe('config reset', () => {
|
describe('config reset', () => {
|
||||||
it('resets to defaults', async () => {
|
it('resets to defaults', async () => {
|
||||||
// First set a custom value
|
// First set a custom value
|
||||||
saveConfig({ ...DEFAULT_CONFIG, daemonUrl: 'http://custom' }, { configDir: tempDir });
|
saveConfig({ ...DEFAULT_CONFIG, mcplocalUrl: 'http://custom' }, { configDir: tempDir });
|
||||||
|
|
||||||
const cmd = makeCommand();
|
const cmd = makeCommand();
|
||||||
await cmd.parseAsync(['reset'], { from: 'user' });
|
await cmd.parseAsync(['reset'], { from: 'user' });
|
||||||
expect(output[0]).toContain('reset');
|
expect(output[0]).toContain('reset');
|
||||||
|
|
||||||
const config = loadConfig({ configDir: tempDir });
|
const config = loadConfig({ configDir: tempDir });
|
||||||
expect(config.daemonUrl).toBe(DEFAULT_CONFIG.daemonUrl);
|
expect(config.mcplocalUrl).toBe(DEFAULT_CONFIG.mcplocalUrl);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
144
src/cli/tests/commands/create.test.ts
Normal file
144
src/cli/tests/commands/create.test.ts
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import { createCreateCommand } from '../../src/commands/create.js';
|
||||||
|
import type { ApiClient } from '../../src/api-client.js';
|
||||||
|
|
||||||
|
function mockClient(): ApiClient {
|
||||||
|
return {
|
||||||
|
get: vi.fn(async () => []),
|
||||||
|
post: vi.fn(async () => ({ id: 'new-id', name: 'test' })),
|
||||||
|
put: vi.fn(async () => ({})),
|
||||||
|
delete: vi.fn(async () => {}),
|
||||||
|
} as unknown as ApiClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('create command', () => {
|
||||||
|
let client: ReturnType<typeof mockClient>;
|
||||||
|
let output: string[];
|
||||||
|
const log = (...args: unknown[]) => output.push(args.map(String).join(' '));
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
client = mockClient();
|
||||||
|
output = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('create server', () => {
|
||||||
|
it('creates a server with minimal flags', async () => {
|
||||||
|
const cmd = createCreateCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['server', 'my-server'], { from: 'user' });
|
||||||
|
expect(client.post).toHaveBeenCalledWith('/api/v1/servers', expect.objectContaining({
|
||||||
|
name: 'my-server',
|
||||||
|
transport: 'STDIO',
|
||||||
|
replicas: 1,
|
||||||
|
}));
|
||||||
|
expect(output.join('\n')).toContain("server 'test' created");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates a server with all flags', async () => {
|
||||||
|
const cmd = createCreateCommand({ client, log });
|
||||||
|
await cmd.parseAsync([
|
||||||
|
'server', 'ha-mcp',
|
||||||
|
'-d', 'Home Assistant MCP',
|
||||||
|
'--docker-image', 'ghcr.io/ha-mcp:latest',
|
||||||
|
'--transport', 'STREAMABLE_HTTP',
|
||||||
|
'--external-url', 'http://localhost:8086/mcp',
|
||||||
|
'--container-port', '3000',
|
||||||
|
'--replicas', '2',
|
||||||
|
'--command', 'python',
|
||||||
|
'--command', '-c',
|
||||||
|
'--command', 'print("hello")',
|
||||||
|
'--env-template', 'API_KEY:API key:true',
|
||||||
|
'--env-template', 'BASE_URL:Base URL:false',
|
||||||
|
], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.post).toHaveBeenCalledWith('/api/v1/servers', {
|
||||||
|
name: 'ha-mcp',
|
||||||
|
description: 'Home Assistant MCP',
|
||||||
|
dockerImage: 'ghcr.io/ha-mcp:latest',
|
||||||
|
transport: 'STREAMABLE_HTTP',
|
||||||
|
externalUrl: 'http://localhost:8086/mcp',
|
||||||
|
containerPort: 3000,
|
||||||
|
replicas: 2,
|
||||||
|
command: ['python', '-c', 'print("hello")'],
|
||||||
|
envTemplate: [
|
||||||
|
{ name: 'API_KEY', description: 'API key', isSecret: true },
|
||||||
|
{ name: 'BASE_URL', description: 'Base URL', isSecret: false },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('defaults transport to STDIO', async () => {
|
||||||
|
const cmd = createCreateCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['server', 'test'], { from: 'user' });
|
||||||
|
expect(client.post).toHaveBeenCalledWith('/api/v1/servers', expect.objectContaining({
|
||||||
|
transport: 'STDIO',
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('create profile', () => {
|
||||||
|
it('creates a profile resolving server name', async () => {
|
||||||
|
vi.mocked(client.get).mockResolvedValue([
|
||||||
|
{ id: 'srv-abc', name: 'ha-mcp' },
|
||||||
|
]);
|
||||||
|
const cmd = createCreateCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['profile', 'production', '--server', 'ha-mcp'], { from: 'user' });
|
||||||
|
expect(client.post).toHaveBeenCalledWith('/api/v1/profiles', expect.objectContaining({
|
||||||
|
name: 'production',
|
||||||
|
serverId: 'srv-abc',
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses --env KEY=value entries', async () => {
|
||||||
|
vi.mocked(client.get).mockResolvedValue([
|
||||||
|
{ id: 'srv-1', name: 'test' },
|
||||||
|
]);
|
||||||
|
const cmd = createCreateCommand({ client, log });
|
||||||
|
await cmd.parseAsync([
|
||||||
|
'profile', 'dev',
|
||||||
|
'--server', 'test',
|
||||||
|
'--env', 'FOO=bar',
|
||||||
|
'--env', 'SECRET=s3cr3t',
|
||||||
|
], { from: 'user' });
|
||||||
|
expect(client.post).toHaveBeenCalledWith('/api/v1/profiles', expect.objectContaining({
|
||||||
|
envOverrides: { FOO: 'bar', SECRET: 's3cr3t' },
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes permissions', async () => {
|
||||||
|
vi.mocked(client.get).mockResolvedValue([
|
||||||
|
{ id: 'srv-1', name: 'test' },
|
||||||
|
]);
|
||||||
|
const cmd = createCreateCommand({ client, log });
|
||||||
|
await cmd.parseAsync([
|
||||||
|
'profile', 'admin',
|
||||||
|
'--server', 'test',
|
||||||
|
'--permissions', 'read',
|
||||||
|
'--permissions', 'write',
|
||||||
|
], { from: 'user' });
|
||||||
|
expect(client.post).toHaveBeenCalledWith('/api/v1/profiles', expect.objectContaining({
|
||||||
|
permissions: ['read', 'write'],
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('create project', () => {
|
||||||
|
it('creates a project', async () => {
|
||||||
|
const cmd = createCreateCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['project', 'my-project', '-d', 'A test project'], { from: 'user' });
|
||||||
|
expect(client.post).toHaveBeenCalledWith('/api/v1/projects', {
|
||||||
|
name: 'my-project',
|
||||||
|
description: 'A test project',
|
||||||
|
});
|
||||||
|
expect(output.join('\n')).toContain("project 'test' created");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates a project with no description', async () => {
|
||||||
|
const cmd = createCreateCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['project', 'minimal'], { from: 'user' });
|
||||||
|
expect(client.post).toHaveBeenCalledWith('/api/v1/projects', {
|
||||||
|
name: 'minimal',
|
||||||
|
description: '',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
129
src/cli/tests/commands/describe.test.ts
Normal file
129
src/cli/tests/commands/describe.test.ts
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
import { describe, it, expect, vi } from 'vitest';
|
||||||
|
import { createDescribeCommand } from '../../src/commands/describe.js';
|
||||||
|
import type { DescribeCommandDeps } from '../../src/commands/describe.js';
|
||||||
|
import type { ApiClient } from '../../src/api-client.js';
|
||||||
|
|
||||||
|
function mockClient(): ApiClient {
|
||||||
|
return {
|
||||||
|
get: vi.fn(async () => []),
|
||||||
|
post: vi.fn(async () => ({})),
|
||||||
|
put: vi.fn(async () => ({})),
|
||||||
|
delete: vi.fn(async () => {}),
|
||||||
|
} as unknown as ApiClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeDeps(item: unknown = {}): DescribeCommandDeps & { output: string[] } {
|
||||||
|
const output: string[] = [];
|
||||||
|
return {
|
||||||
|
output,
|
||||||
|
client: mockClient(),
|
||||||
|
fetchResource: vi.fn(async () => item),
|
||||||
|
log: (...args: string[]) => output.push(args.join(' ')),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('describe command', () => {
|
||||||
|
it('shows detailed server info with sections', async () => {
|
||||||
|
const deps = makeDeps({
|
||||||
|
id: 'srv-1',
|
||||||
|
name: 'slack',
|
||||||
|
transport: 'STDIO',
|
||||||
|
packageName: '@slack/mcp',
|
||||||
|
dockerImage: null,
|
||||||
|
envTemplate: [],
|
||||||
|
createdAt: '2025-01-01',
|
||||||
|
});
|
||||||
|
const cmd = createDescribeCommand(deps);
|
||||||
|
await cmd.parseAsync(['node', 'test', 'server', 'srv-1']);
|
||||||
|
|
||||||
|
expect(deps.fetchResource).toHaveBeenCalledWith('servers', 'srv-1');
|
||||||
|
const text = deps.output.join('\n');
|
||||||
|
expect(text).toContain('=== Server: slack ===');
|
||||||
|
expect(text).toContain('Name:');
|
||||||
|
expect(text).toContain('slack');
|
||||||
|
expect(text).toContain('Transport:');
|
||||||
|
expect(text).toContain('STDIO');
|
||||||
|
expect(text).toContain('Package:');
|
||||||
|
expect(text).toContain('@slack/mcp');
|
||||||
|
expect(text).toContain('Metadata:');
|
||||||
|
expect(text).toContain('ID:');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves resource aliases', async () => {
|
||||||
|
const deps = makeDeps({ id: 'p1' });
|
||||||
|
const cmd = createDescribeCommand(deps);
|
||||||
|
await cmd.parseAsync(['node', 'test', 'prof', 'p1']);
|
||||||
|
expect(deps.fetchResource).toHaveBeenCalledWith('profiles', 'p1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('outputs JSON format', async () => {
|
||||||
|
const deps = makeDeps({ id: 'srv-1', name: 'slack' });
|
||||||
|
const cmd = createDescribeCommand(deps);
|
||||||
|
await cmd.parseAsync(['node', 'test', 'server', 'srv-1', '-o', 'json']);
|
||||||
|
|
||||||
|
const parsed = JSON.parse(deps.output[0] ?? '');
|
||||||
|
expect(parsed.name).toBe('slack');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('outputs YAML format', async () => {
|
||||||
|
const deps = makeDeps({ id: 'srv-1', name: 'slack' });
|
||||||
|
const cmd = createDescribeCommand(deps);
|
||||||
|
await cmd.parseAsync(['node', 'test', 'server', 'srv-1', '-o', 'yaml']);
|
||||||
|
expect(deps.output[0]).toContain('name: slack');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows profile with permissions and env overrides', async () => {
|
||||||
|
const deps = makeDeps({
|
||||||
|
id: 'p1',
|
||||||
|
name: 'production',
|
||||||
|
serverId: 'srv-1',
|
||||||
|
permissions: ['read', 'write'],
|
||||||
|
envOverrides: { FOO: 'bar', SECRET: 's3cr3t' },
|
||||||
|
createdAt: '2025-01-01',
|
||||||
|
});
|
||||||
|
const cmd = createDescribeCommand(deps);
|
||||||
|
await cmd.parseAsync(['node', 'test', 'profile', 'p1']);
|
||||||
|
|
||||||
|
const text = deps.output.join('\n');
|
||||||
|
expect(text).toContain('=== Profile: production ===');
|
||||||
|
expect(text).toContain('read, write');
|
||||||
|
expect(text).toContain('Environment Overrides:');
|
||||||
|
expect(text).toContain('FOO');
|
||||||
|
expect(text).toContain('bar');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows project detail', async () => {
|
||||||
|
const deps = makeDeps({
|
||||||
|
id: 'proj-1',
|
||||||
|
name: 'my-project',
|
||||||
|
description: 'A test project',
|
||||||
|
ownerId: 'user-1',
|
||||||
|
createdAt: '2025-01-01',
|
||||||
|
});
|
||||||
|
const cmd = createDescribeCommand(deps);
|
||||||
|
await cmd.parseAsync(['node', 'test', 'project', 'proj-1']);
|
||||||
|
|
||||||
|
const text = deps.output.join('\n');
|
||||||
|
expect(text).toContain('=== Project: my-project ===');
|
||||||
|
expect(text).toContain('A test project');
|
||||||
|
expect(text).toContain('user-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows instance detail with container info', async () => {
|
||||||
|
const deps = makeDeps({
|
||||||
|
id: 'inst-1',
|
||||||
|
serverId: 'srv-1',
|
||||||
|
status: 'RUNNING',
|
||||||
|
containerId: 'abc123',
|
||||||
|
port: 3000,
|
||||||
|
createdAt: '2025-01-01',
|
||||||
|
});
|
||||||
|
const cmd = createDescribeCommand(deps);
|
||||||
|
await cmd.parseAsync(['node', 'test', 'instance', 'inst-1']);
|
||||||
|
|
||||||
|
const text = deps.output.join('\n');
|
||||||
|
expect(text).toContain('=== Instance: inst-1 ===');
|
||||||
|
expect(text).toContain('RUNNING');
|
||||||
|
expect(text).toContain('abc123');
|
||||||
|
});
|
||||||
|
});
|
||||||
180
src/cli/tests/commands/edit.test.ts
Normal file
180
src/cli/tests/commands/edit.test.ts
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import { readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import yaml from 'js-yaml';
|
||||||
|
import { createEditCommand } from '../../src/commands/edit.js';
|
||||||
|
import type { ApiClient } from '../../src/api-client.js';
|
||||||
|
|
||||||
|
function mockClient(): ApiClient {
|
||||||
|
return {
|
||||||
|
get: vi.fn(async () => ({})),
|
||||||
|
post: vi.fn(async () => ({})),
|
||||||
|
put: vi.fn(async () => ({})),
|
||||||
|
delete: vi.fn(async () => {}),
|
||||||
|
} as unknown as ApiClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('edit command', () => {
|
||||||
|
let client: ReturnType<typeof mockClient>;
|
||||||
|
let output: string[];
|
||||||
|
const log = (...args: unknown[]) => output.push(args.map(String).join(' '));
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
client = mockClient();
|
||||||
|
output = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches server, opens editor, applies changes on save', async () => {
|
||||||
|
// GET /api/v1/servers returns list for resolveNameOrId
|
||||||
|
vi.mocked(client.get).mockImplementation(async (path: string) => {
|
||||||
|
if (path === '/api/v1/servers') {
|
||||||
|
return [{ id: 'srv-1', name: 'ha-mcp' }];
|
||||||
|
}
|
||||||
|
// GET /api/v1/servers/srv-1 returns full server
|
||||||
|
return {
|
||||||
|
id: 'srv-1',
|
||||||
|
name: 'ha-mcp',
|
||||||
|
description: 'Old desc',
|
||||||
|
transport: 'STDIO',
|
||||||
|
replicas: 1,
|
||||||
|
createdAt: '2025-01-01',
|
||||||
|
updatedAt: '2025-01-01',
|
||||||
|
version: 1,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const cmd = createEditCommand({
|
||||||
|
client,
|
||||||
|
log,
|
||||||
|
getEditor: () => 'vi',
|
||||||
|
openEditor: (filePath) => {
|
||||||
|
// Simulate user editing the file
|
||||||
|
const content = readFileSync(filePath, 'utf-8');
|
||||||
|
const modified = content
|
||||||
|
.replace('Old desc', 'New desc')
|
||||||
|
.replace('replicas: 1', 'replicas: 3');
|
||||||
|
writeFileSync(filePath, modified, 'utf-8');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await cmd.parseAsync(['server', 'ha-mcp'], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.put).toHaveBeenCalledWith('/api/v1/servers/srv-1', expect.objectContaining({
|
||||||
|
description: 'New desc',
|
||||||
|
replicas: 3,
|
||||||
|
}));
|
||||||
|
expect(output.join('\n')).toContain("server 'ha-mcp' updated");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('detects no changes and skips PUT', async () => {
|
||||||
|
vi.mocked(client.get).mockImplementation(async (path: string) => {
|
||||||
|
if (path === '/api/v1/servers') return [{ id: 'srv-1', name: 'test' }];
|
||||||
|
return {
|
||||||
|
id: 'srv-1', name: 'test', description: '', transport: 'STDIO',
|
||||||
|
createdAt: '2025-01-01', updatedAt: '2025-01-01', version: 1,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const cmd = createEditCommand({
|
||||||
|
client,
|
||||||
|
log,
|
||||||
|
getEditor: () => 'vi',
|
||||||
|
openEditor: () => {
|
||||||
|
// Don't modify the file
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await cmd.parseAsync(['server', 'test'], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.put).not.toHaveBeenCalled();
|
||||||
|
expect(output.join('\n')).toContain("unchanged");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles empty file as cancel', async () => {
|
||||||
|
vi.mocked(client.get).mockImplementation(async (path: string) => {
|
||||||
|
if (path === '/api/v1/servers') return [{ id: 'srv-1', name: 'test' }];
|
||||||
|
return { id: 'srv-1', name: 'test', createdAt: '2025-01-01', updatedAt: '2025-01-01', version: 1 };
|
||||||
|
});
|
||||||
|
|
||||||
|
const cmd = createEditCommand({
|
||||||
|
client,
|
||||||
|
log,
|
||||||
|
getEditor: () => 'vi',
|
||||||
|
openEditor: (filePath) => {
|
||||||
|
writeFileSync(filePath, '', 'utf-8');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await cmd.parseAsync(['server', 'test'], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.put).not.toHaveBeenCalled();
|
||||||
|
expect(output.join('\n')).toContain('cancelled');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('strips read-only fields from editor content', async () => {
|
||||||
|
vi.mocked(client.get).mockImplementation(async (path: string) => {
|
||||||
|
if (path === '/api/v1/servers') return [{ id: 'srv-1', name: 'test' }];
|
||||||
|
return {
|
||||||
|
id: 'srv-1', name: 'test', description: '', transport: 'STDIO',
|
||||||
|
createdAt: '2025-01-01', updatedAt: '2025-01-01', version: 1,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
let editorContent = '';
|
||||||
|
const cmd = createEditCommand({
|
||||||
|
client,
|
||||||
|
log,
|
||||||
|
getEditor: () => 'vi',
|
||||||
|
openEditor: (filePath) => {
|
||||||
|
editorContent = readFileSync(filePath, 'utf-8');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await cmd.parseAsync(['server', 'test'], { from: 'user' });
|
||||||
|
|
||||||
|
// The editor content should NOT contain read-only fields
|
||||||
|
expect(editorContent).not.toContain('id:');
|
||||||
|
expect(editorContent).not.toContain('createdAt');
|
||||||
|
expect(editorContent).not.toContain('updatedAt');
|
||||||
|
expect(editorContent).not.toContain('version');
|
||||||
|
// But should contain editable fields
|
||||||
|
expect(editorContent).toContain('name:');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects edit instance with error message', async () => {
|
||||||
|
const cmd = createEditCommand({ client, log });
|
||||||
|
|
||||||
|
await cmd.parseAsync(['instance', 'inst-1'], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.get).not.toHaveBeenCalled();
|
||||||
|
expect(client.put).not.toHaveBeenCalled();
|
||||||
|
expect(output.join('\n')).toContain('immutable');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('edits a profile', async () => {
|
||||||
|
vi.mocked(client.get).mockImplementation(async (path: string) => {
|
||||||
|
if (path === '/api/v1/profiles') return [{ id: 'prof-1', name: 'production' }];
|
||||||
|
return {
|
||||||
|
id: 'prof-1', name: 'production', serverId: 'srv-1',
|
||||||
|
permissions: ['read'], envOverrides: { FOO: 'bar' },
|
||||||
|
createdAt: '2025-01-01', updatedAt: '2025-01-01', version: 1,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const cmd = createEditCommand({
|
||||||
|
client,
|
||||||
|
log,
|
||||||
|
getEditor: () => 'vi',
|
||||||
|
openEditor: (filePath) => {
|
||||||
|
const content = readFileSync(filePath, 'utf-8');
|
||||||
|
const modified = content.replace('FOO: bar', 'FOO: baz');
|
||||||
|
writeFileSync(filePath, modified, 'utf-8');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await cmd.parseAsync(['profile', 'production'], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.put).toHaveBeenCalledWith('/api/v1/profiles/prof-1', expect.objectContaining({
|
||||||
|
envOverrides: { FOO: 'baz' },
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
});
|
||||||
96
src/cli/tests/commands/get.test.ts
Normal file
96
src/cli/tests/commands/get.test.ts
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
import { describe, it, expect, vi } from 'vitest';
|
||||||
|
import { createGetCommand } from '../../src/commands/get.js';
|
||||||
|
import type { GetCommandDeps } from '../../src/commands/get.js';
|
||||||
|
|
||||||
|
function makeDeps(items: unknown[] = []): GetCommandDeps & { output: string[] } {
|
||||||
|
const output: string[] = [];
|
||||||
|
return {
|
||||||
|
output,
|
||||||
|
fetchResource: vi.fn(async () => items),
|
||||||
|
log: (...args: string[]) => output.push(args.join(' ')),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('get command', () => {
|
||||||
|
it('lists servers in table format', async () => {
|
||||||
|
const deps = makeDeps([
|
||||||
|
{ id: 'srv-1', name: 'slack', transport: 'STDIO', packageName: '@slack/mcp', dockerImage: null },
|
||||||
|
{ id: 'srv-2', name: 'github', transport: 'SSE', packageName: null, dockerImage: 'ghcr.io/github-mcp' },
|
||||||
|
]);
|
||||||
|
const cmd = createGetCommand(deps);
|
||||||
|
await cmd.parseAsync(['node', 'test', 'servers']);
|
||||||
|
|
||||||
|
expect(deps.fetchResource).toHaveBeenCalledWith('servers', undefined);
|
||||||
|
expect(deps.output[0]).toContain('NAME');
|
||||||
|
expect(deps.output[0]).toContain('TRANSPORT');
|
||||||
|
expect(deps.output.join('\n')).toContain('slack');
|
||||||
|
expect(deps.output.join('\n')).toContain('github');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves resource aliases', async () => {
|
||||||
|
const deps = makeDeps([]);
|
||||||
|
const cmd = createGetCommand(deps);
|
||||||
|
await cmd.parseAsync(['node', 'test', 'srv']);
|
||||||
|
expect(deps.fetchResource).toHaveBeenCalledWith('servers', undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes ID when provided', async () => {
|
||||||
|
const deps = makeDeps([{ id: 'srv-1', name: 'slack' }]);
|
||||||
|
const cmd = createGetCommand(deps);
|
||||||
|
await cmd.parseAsync(['node', 'test', 'servers', 'srv-1']);
|
||||||
|
expect(deps.fetchResource).toHaveBeenCalledWith('servers', 'srv-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('outputs apply-compatible JSON format', async () => {
|
||||||
|
const deps = makeDeps([{ id: 'srv-1', name: 'slack', createdAt: '2025-01-01', updatedAt: '2025-01-01', version: 1 }]);
|
||||||
|
const cmd = createGetCommand(deps);
|
||||||
|
await cmd.parseAsync(['node', 'test', 'servers', '-o', 'json']);
|
||||||
|
|
||||||
|
const parsed = JSON.parse(deps.output[0] ?? '');
|
||||||
|
// Wrapped in resource key, internal fields stripped
|
||||||
|
expect(parsed).toHaveProperty('servers');
|
||||||
|
expect(parsed.servers[0].name).toBe('slack');
|
||||||
|
expect(parsed.servers[0]).not.toHaveProperty('id');
|
||||||
|
expect(parsed.servers[0]).not.toHaveProperty('createdAt');
|
||||||
|
expect(parsed.servers[0]).not.toHaveProperty('updatedAt');
|
||||||
|
expect(parsed.servers[0]).not.toHaveProperty('version');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('outputs apply-compatible YAML format', async () => {
|
||||||
|
const deps = makeDeps([{ id: 'srv-1', name: 'slack', createdAt: '2025-01-01' }]);
|
||||||
|
const cmd = createGetCommand(deps);
|
||||||
|
await cmd.parseAsync(['node', 'test', 'servers', '-o', 'yaml']);
|
||||||
|
const text = deps.output[0];
|
||||||
|
expect(text).toContain('servers:');
|
||||||
|
expect(text).toContain('name: slack');
|
||||||
|
expect(text).not.toContain('id:');
|
||||||
|
expect(text).not.toContain('createdAt:');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists profiles with correct columns', async () => {
|
||||||
|
const deps = makeDeps([
|
||||||
|
{ id: 'p1', name: 'default', serverId: 'srv-1' },
|
||||||
|
]);
|
||||||
|
const cmd = createGetCommand(deps);
|
||||||
|
await cmd.parseAsync(['node', 'test', 'profiles']);
|
||||||
|
expect(deps.output[0]).toContain('NAME');
|
||||||
|
expect(deps.output[0]).toContain('SERVER ID');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists instances with correct columns', async () => {
|
||||||
|
const deps = makeDeps([
|
||||||
|
{ id: 'inst-1', serverId: 'srv-1', status: 'RUNNING', containerId: 'abc123def456', port: 3000 },
|
||||||
|
]);
|
||||||
|
const cmd = createGetCommand(deps);
|
||||||
|
await cmd.parseAsync(['node', 'test', 'instances']);
|
||||||
|
expect(deps.output[0]).toContain('STATUS');
|
||||||
|
expect(deps.output.join('\n')).toContain('RUNNING');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows no results message for empty list', async () => {
|
||||||
|
const deps = makeDeps([]);
|
||||||
|
const cmd = createGetCommand(deps);
|
||||||
|
await cmd.parseAsync(['node', 'test', 'servers']);
|
||||||
|
expect(deps.output[0]).toContain('No servers found');
|
||||||
|
});
|
||||||
|
});
|
||||||
91
src/cli/tests/commands/instances.test.ts
Normal file
91
src/cli/tests/commands/instances.test.ts
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import { createDeleteCommand } from '../../src/commands/delete.js';
|
||||||
|
import { createLogsCommand } from '../../src/commands/logs.js';
|
||||||
|
import type { ApiClient } from '../../src/api-client.js';
|
||||||
|
|
||||||
|
function mockClient(): ApiClient {
|
||||||
|
return {
|
||||||
|
get: vi.fn(async () => []),
|
||||||
|
post: vi.fn(async () => ({})),
|
||||||
|
put: vi.fn(async () => ({})),
|
||||||
|
delete: vi.fn(async () => {}),
|
||||||
|
} as unknown as ApiClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('delete command', () => {
|
||||||
|
let client: ReturnType<typeof mockClient>;
|
||||||
|
let output: string[];
|
||||||
|
const log = (...args: unknown[]) => output.push(args.map(String).join(' '));
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
client = mockClient();
|
||||||
|
output = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes an instance by ID', async () => {
|
||||||
|
const cmd = createDeleteCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['instance', 'inst-1'], { from: 'user' });
|
||||||
|
expect(client.delete).toHaveBeenCalledWith('/api/v1/instances/inst-1');
|
||||||
|
expect(output.join('\n')).toContain('deleted');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes a server by ID', async () => {
|
||||||
|
const cmd = createDeleteCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['server', 'srv-1'], { from: 'user' });
|
||||||
|
expect(client.delete).toHaveBeenCalledWith('/api/v1/servers/srv-1');
|
||||||
|
expect(output.join('\n')).toContain('deleted');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves server name to ID', async () => {
|
||||||
|
vi.mocked(client.get).mockResolvedValue([
|
||||||
|
{ id: 'srv-abc', name: 'ha-mcp' },
|
||||||
|
]);
|
||||||
|
const cmd = createDeleteCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['server', 'ha-mcp'], { from: 'user' });
|
||||||
|
expect(client.delete).toHaveBeenCalledWith('/api/v1/servers/srv-abc');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes a profile', async () => {
|
||||||
|
const cmd = createDeleteCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['profile', 'prof-1'], { from: 'user' });
|
||||||
|
expect(client.delete).toHaveBeenCalledWith('/api/v1/profiles/prof-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes a project', async () => {
|
||||||
|
const cmd = createDeleteCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['project', 'proj-1'], { from: 'user' });
|
||||||
|
expect(client.delete).toHaveBeenCalledWith('/api/v1/projects/proj-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts resource aliases', async () => {
|
||||||
|
const cmd = createDeleteCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['srv', 'srv-1'], { from: 'user' });
|
||||||
|
expect(client.delete).toHaveBeenCalledWith('/api/v1/servers/srv-1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('logs command', () => {
|
||||||
|
let client: ReturnType<typeof mockClient>;
|
||||||
|
let output: string[];
|
||||||
|
const log = (...args: unknown[]) => output.push(args.map(String).join(' '));
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
client = mockClient();
|
||||||
|
output = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows logs', async () => {
|
||||||
|
vi.mocked(client.get).mockResolvedValue({ stdout: 'hello world\n', stderr: '' });
|
||||||
|
const cmd = createLogsCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['inst-1'], { from: 'user' });
|
||||||
|
expect(client.get).toHaveBeenCalledWith('/api/v1/instances/inst-1/logs');
|
||||||
|
expect(output.join('\n')).toContain('hello world');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes tail option', async () => {
|
||||||
|
vi.mocked(client.get).mockResolvedValue({ stdout: '', stderr: '' });
|
||||||
|
const cmd = createLogsCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['inst-1', '-t', '50'], { from: 'user' });
|
||||||
|
expect(client.get).toHaveBeenCalledWith('/api/v1/instances/inst-1/logs?tail=50');
|
||||||
|
});
|
||||||
|
});
|
||||||
52
src/cli/tests/commands/project.test.ts
Normal file
52
src/cli/tests/commands/project.test.ts
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import { createProjectCommand } from '../../src/commands/project.js';
|
||||||
|
import type { ApiClient } from '../../src/api-client.js';
|
||||||
|
|
||||||
|
function mockClient(): ApiClient {
|
||||||
|
return {
|
||||||
|
get: vi.fn(async () => []),
|
||||||
|
post: vi.fn(async () => ({ id: 'proj-1', name: 'my-project' })),
|
||||||
|
put: vi.fn(async () => ({})),
|
||||||
|
delete: vi.fn(async () => {}),
|
||||||
|
} as unknown as ApiClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('project command', () => {
|
||||||
|
let client: ReturnType<typeof mockClient>;
|
||||||
|
let output: string[];
|
||||||
|
const log = (...args: unknown[]) => output.push(args.map(String).join(' '));
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
client = mockClient();
|
||||||
|
output = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('profiles', () => {
|
||||||
|
it('lists profiles for a project', async () => {
|
||||||
|
vi.mocked(client.get).mockResolvedValue([
|
||||||
|
{ id: 'prof-1', name: 'default', serverId: 'srv-1' },
|
||||||
|
]);
|
||||||
|
const cmd = createProjectCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['profiles', 'proj-1'], { from: 'user' });
|
||||||
|
expect(client.get).toHaveBeenCalledWith('/api/v1/projects/proj-1/profiles');
|
||||||
|
expect(output.join('\n')).toContain('default');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows empty message when no profiles', async () => {
|
||||||
|
const cmd = createProjectCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['profiles', 'proj-1'], { from: 'user' });
|
||||||
|
expect(output.join('\n')).toContain('No profiles assigned');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('set-profiles', () => {
|
||||||
|
it('sets profiles for a project', async () => {
|
||||||
|
const cmd = createProjectCommand({ client, log });
|
||||||
|
await cmd.parseAsync(['set-profiles', 'proj-1', 'prof-1', 'prof-2'], { from: 'user' });
|
||||||
|
expect(client.put).toHaveBeenCalledWith('/api/v1/projects/proj-1/profiles', {
|
||||||
|
profileIds: ['prof-1', 'prof-2'],
|
||||||
|
});
|
||||||
|
expect(output.join('\n')).toContain('2 profile(s)');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
141
src/cli/tests/commands/setup.test.ts
Normal file
141
src/cli/tests/commands/setup.test.ts
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import { createSetupCommand } from '../../src/commands/setup.js';
|
||||||
|
import type { ApiClient } from '../../src/api-client.js';
|
||||||
|
import type { SetupPromptDeps } from '../../src/commands/setup.js';
|
||||||
|
|
||||||
|
function mockClient(): ApiClient {
|
||||||
|
return {
|
||||||
|
get: vi.fn(async () => []),
|
||||||
|
post: vi.fn(async () => ({ id: 'new-id', name: 'test' })),
|
||||||
|
put: vi.fn(async () => ({})),
|
||||||
|
delete: vi.fn(async () => {}),
|
||||||
|
} as unknown as ApiClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mockPrompt(answers: Record<string, string | boolean>): SetupPromptDeps {
|
||||||
|
const answersQueue = { ...answers };
|
||||||
|
return {
|
||||||
|
input: vi.fn(async (message: string) => {
|
||||||
|
for (const [key, val] of Object.entries(answersQueue)) {
|
||||||
|
if (message.toLowerCase().includes(key.toLowerCase()) && typeof val === 'string') {
|
||||||
|
delete answersQueue[key];
|
||||||
|
return val;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}),
|
||||||
|
password: vi.fn(async () => 'secret-value'),
|
||||||
|
select: vi.fn(async () => 'STDIO') as SetupPromptDeps['select'],
|
||||||
|
confirm: vi.fn(async (message: string) => {
|
||||||
|
if (message.includes('profile')) return true;
|
||||||
|
if (message.includes('secret')) return false;
|
||||||
|
if (message.includes('another')) return false;
|
||||||
|
return false;
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('setup command', () => {
|
||||||
|
let client: ReturnType<typeof mockClient>;
|
||||||
|
let output: string[];
|
||||||
|
const log = (...args: unknown[]) => output.push(args.map(String).join(' '));
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
client = mockClient();
|
||||||
|
output = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates server with prompted values', async () => {
|
||||||
|
const prompt = mockPrompt({
|
||||||
|
'transport': 'STDIO',
|
||||||
|
'npm package': '@anthropic/slack-mcp',
|
||||||
|
'docker image': '',
|
||||||
|
'description': 'Slack server',
|
||||||
|
'profile name': 'default',
|
||||||
|
'environment variable name': '',
|
||||||
|
});
|
||||||
|
|
||||||
|
const cmd = createSetupCommand({ client, prompt, log });
|
||||||
|
await cmd.parseAsync(['slack'], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.post).toHaveBeenCalledWith('/api/v1/servers', expect.objectContaining({
|
||||||
|
name: 'slack',
|
||||||
|
transport: 'STDIO',
|
||||||
|
}));
|
||||||
|
expect(output.join('\n')).toContain("Server 'test' created");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates profile with env vars', async () => {
|
||||||
|
vi.mocked(client.post)
|
||||||
|
.mockResolvedValueOnce({ id: 'srv-1', name: 'slack' }) // server create
|
||||||
|
.mockResolvedValueOnce({ id: 'prof-1', name: 'default' }); // profile create
|
||||||
|
|
||||||
|
const prompt = mockPrompt({
|
||||||
|
'transport': 'STDIO',
|
||||||
|
'npm package': '',
|
||||||
|
'docker image': '',
|
||||||
|
'description': '',
|
||||||
|
'profile name': 'default',
|
||||||
|
});
|
||||||
|
// Override confirm to create profile and add one env var
|
||||||
|
let confirmCallCount = 0;
|
||||||
|
vi.mocked(prompt.confirm).mockImplementation(async (msg: string) => {
|
||||||
|
confirmCallCount++;
|
||||||
|
if (msg.includes('profile')) return true;
|
||||||
|
if (msg.includes('secret')) return true;
|
||||||
|
if (msg.includes('another')) return false;
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
// Override input to provide env var name then empty to stop
|
||||||
|
let inputCallCount = 0;
|
||||||
|
vi.mocked(prompt.input).mockImplementation(async (msg: string) => {
|
||||||
|
inputCallCount++;
|
||||||
|
if (msg.includes('Profile name')) return 'default';
|
||||||
|
if (msg.includes('variable name') && inputCallCount <= 8) return 'API_KEY';
|
||||||
|
if (msg.includes('variable name')) return '';
|
||||||
|
return '';
|
||||||
|
});
|
||||||
|
|
||||||
|
const cmd = createSetupCommand({ client, prompt, log });
|
||||||
|
await cmd.parseAsync(['slack'], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.post).toHaveBeenCalledTimes(2);
|
||||||
|
const profileCall = vi.mocked(client.post).mock.calls[1];
|
||||||
|
expect(profileCall?.[0]).toBe('/api/v1/profiles');
|
||||||
|
expect(profileCall?.[1]).toEqual(expect.objectContaining({
|
||||||
|
name: 'default',
|
||||||
|
serverId: 'srv-1',
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('exits if server creation fails', async () => {
|
||||||
|
vi.mocked(client.post).mockRejectedValue(new Error('conflict'));
|
||||||
|
|
||||||
|
const prompt = mockPrompt({
|
||||||
|
'npm package': '',
|
||||||
|
'docker image': '',
|
||||||
|
'description': '',
|
||||||
|
});
|
||||||
|
|
||||||
|
const cmd = createSetupCommand({ client, prompt, log });
|
||||||
|
await cmd.parseAsync(['slack'], { from: 'user' });
|
||||||
|
|
||||||
|
expect(output.join('\n')).toContain('Failed to create server');
|
||||||
|
expect(client.post).toHaveBeenCalledTimes(1); // Only server create, no profile
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips profile creation when declined', async () => {
|
||||||
|
const prompt = mockPrompt({
|
||||||
|
'npm package': '',
|
||||||
|
'docker image': '',
|
||||||
|
'description': '',
|
||||||
|
});
|
||||||
|
vi.mocked(prompt.confirm).mockResolvedValue(false);
|
||||||
|
|
||||||
|
const cmd = createSetupCommand({ client, prompt, log });
|
||||||
|
await cmd.parseAsync(['test-server'], { from: 'user' });
|
||||||
|
|
||||||
|
expect(client.post).toHaveBeenCalledTimes(1); // Only server create
|
||||||
|
expect(output.join('\n')).toContain('Setup complete');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,6 +4,7 @@ import { join } from 'node:path';
|
|||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { createStatusCommand } from '../../src/commands/status.js';
|
import { createStatusCommand } from '../../src/commands/status.js';
|
||||||
import { saveConfig, DEFAULT_CONFIG } from '../../src/config/index.js';
|
import { saveConfig, DEFAULT_CONFIG } from '../../src/config/index.js';
|
||||||
|
import { saveCredentials } from '../../src/auth/index.js';
|
||||||
|
|
||||||
let tempDir: string;
|
let tempDir: string;
|
||||||
let output: string[];
|
let output: string[];
|
||||||
@@ -25,67 +26,101 @@ describe('status command', () => {
|
|||||||
it('shows status in table format', async () => {
|
it('shows status in table format', async () => {
|
||||||
const cmd = createStatusCommand({
|
const cmd = createStatusCommand({
|
||||||
configDeps: { configDir: tempDir },
|
configDeps: { configDir: tempDir },
|
||||||
|
credentialsDeps: { configDir: tempDir },
|
||||||
log,
|
log,
|
||||||
checkDaemon: async () => true,
|
checkHealth: async () => true,
|
||||||
});
|
});
|
||||||
await cmd.parseAsync([], { from: 'user' });
|
await cmd.parseAsync([], { from: 'user' });
|
||||||
expect(output.join('\n')).toContain('mcpctl v');
|
const out = output.join('\n');
|
||||||
expect(output.join('\n')).toContain('connected');
|
expect(out).toContain('mcpctl v');
|
||||||
|
expect(out).toContain('mcplocal:');
|
||||||
|
expect(out).toContain('mcpd:');
|
||||||
|
expect(out).toContain('connected');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows unreachable when daemon is down', async () => {
|
it('shows unreachable when daemons are down', async () => {
|
||||||
const cmd = createStatusCommand({
|
const cmd = createStatusCommand({
|
||||||
configDeps: { configDir: tempDir },
|
configDeps: { configDir: tempDir },
|
||||||
|
credentialsDeps: { configDir: tempDir },
|
||||||
log,
|
log,
|
||||||
checkDaemon: async () => false,
|
checkHealth: async () => false,
|
||||||
});
|
});
|
||||||
await cmd.parseAsync([], { from: 'user' });
|
await cmd.parseAsync([], { from: 'user' });
|
||||||
expect(output.join('\n')).toContain('unreachable');
|
expect(output.join('\n')).toContain('unreachable');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('shows not logged in when no credentials', async () => {
|
||||||
|
const cmd = createStatusCommand({
|
||||||
|
configDeps: { configDir: tempDir },
|
||||||
|
credentialsDeps: { configDir: tempDir },
|
||||||
|
log,
|
||||||
|
checkHealth: async () => true,
|
||||||
|
});
|
||||||
|
await cmd.parseAsync([], { from: 'user' });
|
||||||
|
expect(output.join('\n')).toContain('not logged in');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows logged in user when credentials exist', async () => {
|
||||||
|
saveCredentials({ token: 'tok', mcpdUrl: 'http://x:3100', user: 'alice@example.com' }, { configDir: tempDir });
|
||||||
|
const cmd = createStatusCommand({
|
||||||
|
configDeps: { configDir: tempDir },
|
||||||
|
credentialsDeps: { configDir: tempDir },
|
||||||
|
log,
|
||||||
|
checkHealth: async () => true,
|
||||||
|
});
|
||||||
|
await cmd.parseAsync([], { from: 'user' });
|
||||||
|
expect(output.join('\n')).toContain('logged in as alice@example.com');
|
||||||
|
});
|
||||||
|
|
||||||
it('shows status in JSON format', async () => {
|
it('shows status in JSON format', async () => {
|
||||||
const cmd = createStatusCommand({
|
const cmd = createStatusCommand({
|
||||||
configDeps: { configDir: tempDir },
|
configDeps: { configDir: tempDir },
|
||||||
|
credentialsDeps: { configDir: tempDir },
|
||||||
log,
|
log,
|
||||||
checkDaemon: async () => true,
|
checkHealth: async () => true,
|
||||||
});
|
});
|
||||||
await cmd.parseAsync(['-o', 'json'], { from: 'user' });
|
await cmd.parseAsync(['-o', 'json'], { from: 'user' });
|
||||||
const parsed = JSON.parse(output[0]) as Record<string, unknown>;
|
const parsed = JSON.parse(output[0]) as Record<string, unknown>;
|
||||||
expect(parsed['version']).toBe('0.1.0');
|
expect(parsed['version']).toBe('0.1.0');
|
||||||
expect(parsed['daemonReachable']).toBe(true);
|
expect(parsed['mcplocalReachable']).toBe(true);
|
||||||
|
expect(parsed['mcpdReachable']).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows status in YAML format', async () => {
|
it('shows status in YAML format', async () => {
|
||||||
const cmd = createStatusCommand({
|
const cmd = createStatusCommand({
|
||||||
configDeps: { configDir: tempDir },
|
configDeps: { configDir: tempDir },
|
||||||
|
credentialsDeps: { configDir: tempDir },
|
||||||
log,
|
log,
|
||||||
checkDaemon: async () => false,
|
checkHealth: async () => false,
|
||||||
});
|
});
|
||||||
await cmd.parseAsync(['-o', 'yaml'], { from: 'user' });
|
await cmd.parseAsync(['-o', 'yaml'], { from: 'user' });
|
||||||
expect(output[0]).toContain('daemonReachable: false');
|
expect(output[0]).toContain('mcplocalReachable: false');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('uses custom daemon URL from config', async () => {
|
it('checks correct URLs from config', async () => {
|
||||||
saveConfig({ ...DEFAULT_CONFIG, daemonUrl: 'http://custom:5555' }, { configDir: tempDir });
|
saveConfig({ ...DEFAULT_CONFIG, mcplocalUrl: 'http://local:3200', mcpdUrl: 'http://remote:3100' }, { configDir: tempDir });
|
||||||
let checkedUrl = '';
|
const checkedUrls: string[] = [];
|
||||||
const cmd = createStatusCommand({
|
const cmd = createStatusCommand({
|
||||||
configDeps: { configDir: tempDir },
|
configDeps: { configDir: tempDir },
|
||||||
|
credentialsDeps: { configDir: tempDir },
|
||||||
log,
|
log,
|
||||||
checkDaemon: async (url) => {
|
checkHealth: async (url) => {
|
||||||
checkedUrl = url;
|
checkedUrls.push(url);
|
||||||
return false;
|
return false;
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
await cmd.parseAsync([], { from: 'user' });
|
await cmd.parseAsync([], { from: 'user' });
|
||||||
expect(checkedUrl).toBe('http://custom:5555');
|
expect(checkedUrls).toContain('http://local:3200');
|
||||||
|
expect(checkedUrls).toContain('http://remote:3100');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows registries from config', async () => {
|
it('shows registries from config', async () => {
|
||||||
saveConfig({ ...DEFAULT_CONFIG, registries: ['official'] }, { configDir: tempDir });
|
saveConfig({ ...DEFAULT_CONFIG, registries: ['official'] }, { configDir: tempDir });
|
||||||
const cmd = createStatusCommand({
|
const cmd = createStatusCommand({
|
||||||
configDeps: { configDir: tempDir },
|
configDeps: { configDir: tempDir },
|
||||||
|
credentialsDeps: { configDir: tempDir },
|
||||||
log,
|
log,
|
||||||
checkDaemon: async () => true,
|
checkHealth: async () => true,
|
||||||
});
|
});
|
||||||
await cmd.parseAsync([], { from: 'user' });
|
await cmd.parseAsync([], { from: 'user' });
|
||||||
expect(output.join('\n')).toContain('official');
|
expect(output.join('\n')).toContain('official');
|
||||||
|
|||||||
@@ -28,18 +28,25 @@ describe('loadConfig', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('loads config from file', () => {
|
it('loads config from file', () => {
|
||||||
saveConfig({ ...DEFAULT_CONFIG, daemonUrl: 'http://custom:5000' }, { configDir: tempDir });
|
saveConfig({ ...DEFAULT_CONFIG, mcplocalUrl: 'http://custom:5000' }, { configDir: tempDir });
|
||||||
const config = loadConfig({ configDir: tempDir });
|
const config = loadConfig({ configDir: tempDir });
|
||||||
expect(config.daemonUrl).toBe('http://custom:5000');
|
expect(config.mcplocalUrl).toBe('http://custom:5000');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('applies defaults for missing fields', () => {
|
it('applies defaults for missing fields', () => {
|
||||||
const { writeFileSync } = require('node:fs') as typeof import('node:fs');
|
const { writeFileSync } = require('node:fs') as typeof import('node:fs');
|
||||||
writeFileSync(join(tempDir, 'config.json'), '{"daemonUrl":"http://x:1"}');
|
writeFileSync(join(tempDir, 'config.json'), '{"mcplocalUrl":"http://x:1"}');
|
||||||
const config = loadConfig({ configDir: tempDir });
|
const config = loadConfig({ configDir: tempDir });
|
||||||
expect(config.daemonUrl).toBe('http://x:1');
|
expect(config.mcplocalUrl).toBe('http://x:1');
|
||||||
expect(config.registries).toEqual(['official', 'glama', 'smithery']);
|
expect(config.registries).toEqual(['official', 'glama', 'smithery']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('backward compat: daemonUrl maps to mcplocalUrl', () => {
|
||||||
|
const { writeFileSync } = require('node:fs') as typeof import('node:fs');
|
||||||
|
writeFileSync(join(tempDir, 'config.json'), '{"daemonUrl":"http://old:3000"}');
|
||||||
|
const config = loadConfig({ configDir: tempDir });
|
||||||
|
expect(config.mcplocalUrl).toBe('http://old:3000');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('saveConfig', () => {
|
describe('saveConfig', () => {
|
||||||
@@ -57,7 +64,7 @@ describe('saveConfig', () => {
|
|||||||
it('round-trips configuration', () => {
|
it('round-trips configuration', () => {
|
||||||
const custom = {
|
const custom = {
|
||||||
...DEFAULT_CONFIG,
|
...DEFAULT_CONFIG,
|
||||||
daemonUrl: 'http://custom:9000',
|
mcplocalUrl: 'http://custom:9000',
|
||||||
registries: ['official' as const],
|
registries: ['official' as const],
|
||||||
outputFormat: 'json' as const,
|
outputFormat: 'json' as const,
|
||||||
};
|
};
|
||||||
@@ -70,14 +77,14 @@ describe('saveConfig', () => {
|
|||||||
describe('mergeConfig', () => {
|
describe('mergeConfig', () => {
|
||||||
it('merges overrides into existing config', () => {
|
it('merges overrides into existing config', () => {
|
||||||
saveConfig(DEFAULT_CONFIG, { configDir: tempDir });
|
saveConfig(DEFAULT_CONFIG, { configDir: tempDir });
|
||||||
const merged = mergeConfig({ daemonUrl: 'http://new:1234' }, { configDir: tempDir });
|
const merged = mergeConfig({ mcplocalUrl: 'http://new:1234' }, { configDir: tempDir });
|
||||||
expect(merged.daemonUrl).toBe('http://new:1234');
|
expect(merged.mcplocalUrl).toBe('http://new:1234');
|
||||||
expect(merged.registries).toEqual(DEFAULT_CONFIG.registries);
|
expect(merged.registries).toEqual(DEFAULT_CONFIG.registries);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('works when no config file exists', () => {
|
it('works when no config file exists', () => {
|
||||||
const merged = mergeConfig({ outputFormat: 'yaml' }, { configDir: tempDir });
|
const merged = mergeConfig({ outputFormat: 'yaml' }, { configDir: tempDir });
|
||||||
expect(merged.outputFormat).toBe('yaml');
|
expect(merged.outputFormat).toBe('yaml');
|
||||||
expect(merged.daemonUrl).toBe('http://localhost:3000');
|
expect(merged.mcplocalUrl).toBe('http://localhost:3200');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ import { McpctlConfigSchema, DEFAULT_CONFIG } from '../../src/config/schema.js';
|
|||||||
describe('McpctlConfigSchema', () => {
|
describe('McpctlConfigSchema', () => {
|
||||||
it('provides sensible defaults from empty object', () => {
|
it('provides sensible defaults from empty object', () => {
|
||||||
const config = McpctlConfigSchema.parse({});
|
const config = McpctlConfigSchema.parse({});
|
||||||
expect(config.daemonUrl).toBe('http://localhost:3000');
|
expect(config.mcplocalUrl).toBe('http://localhost:3200');
|
||||||
|
expect(config.mcpdUrl).toBe('http://localhost:3100');
|
||||||
expect(config.registries).toEqual(['official', 'glama', 'smithery']);
|
expect(config.registries).toEqual(['official', 'glama', 'smithery']);
|
||||||
expect(config.cacheTTLMs).toBe(3_600_000);
|
expect(config.cacheTTLMs).toBe(3_600_000);
|
||||||
expect(config.outputFormat).toBe('table');
|
expect(config.outputFormat).toBe('table');
|
||||||
@@ -15,7 +16,8 @@ describe('McpctlConfigSchema', () => {
|
|||||||
|
|
||||||
it('validates a full config', () => {
|
it('validates a full config', () => {
|
||||||
const config = McpctlConfigSchema.parse({
|
const config = McpctlConfigSchema.parse({
|
||||||
daemonUrl: 'http://custom:4000',
|
mcplocalUrl: 'http://local:3200',
|
||||||
|
mcpdUrl: 'http://custom:4000',
|
||||||
registries: ['official'],
|
registries: ['official'],
|
||||||
cacheTTLMs: 60_000,
|
cacheTTLMs: 60_000,
|
||||||
httpProxy: 'http://proxy:8080',
|
httpProxy: 'http://proxy:8080',
|
||||||
@@ -23,11 +25,26 @@ describe('McpctlConfigSchema', () => {
|
|||||||
outputFormat: 'json',
|
outputFormat: 'json',
|
||||||
smitheryApiKey: 'sk-test',
|
smitheryApiKey: 'sk-test',
|
||||||
});
|
});
|
||||||
expect(config.daemonUrl).toBe('http://custom:4000');
|
expect(config.mcplocalUrl).toBe('http://local:3200');
|
||||||
|
expect(config.mcpdUrl).toBe('http://custom:4000');
|
||||||
expect(config.registries).toEqual(['official']);
|
expect(config.registries).toEqual(['official']);
|
||||||
expect(config.outputFormat).toBe('json');
|
expect(config.outputFormat).toBe('json');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('backward compat: maps daemonUrl to mcplocalUrl', () => {
|
||||||
|
const config = McpctlConfigSchema.parse({ daemonUrl: 'http://legacy:3000' });
|
||||||
|
expect(config.mcplocalUrl).toBe('http://legacy:3000');
|
||||||
|
expect(config.mcpdUrl).toBe('http://localhost:3100');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('mcplocalUrl takes precedence over daemonUrl', () => {
|
||||||
|
const config = McpctlConfigSchema.parse({
|
||||||
|
daemonUrl: 'http://legacy:3000',
|
||||||
|
mcplocalUrl: 'http://explicit:3200',
|
||||||
|
});
|
||||||
|
expect(config.mcplocalUrl).toBe('http://explicit:3200');
|
||||||
|
});
|
||||||
|
|
||||||
it('rejects invalid registry names', () => {
|
it('rejects invalid registry names', () => {
|
||||||
expect(() => McpctlConfigSchema.parse({ registries: ['invalid'] })).toThrow();
|
expect(() => McpctlConfigSchema.parse({ registries: ['invalid'] })).toThrow();
|
||||||
});
|
});
|
||||||
|
|||||||
76
src/cli/tests/e2e/cli-commands.test.ts
Normal file
76
src/cli/tests/e2e/cli-commands.test.ts
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { createProgram } from '../../src/index.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* End-to-end tests that verify CLI command registration and help output
|
||||||
|
* without requiring a running daemon.
|
||||||
|
*/
|
||||||
|
describe('CLI command registration (e2e)', () => {
|
||||||
|
it('program has all expected commands', () => {
|
||||||
|
const program = createProgram();
|
||||||
|
const commandNames = program.commands.map((c) => c.name());
|
||||||
|
|
||||||
|
expect(commandNames).toContain('config');
|
||||||
|
expect(commandNames).toContain('status');
|
||||||
|
expect(commandNames).toContain('login');
|
||||||
|
expect(commandNames).toContain('logout');
|
||||||
|
expect(commandNames).toContain('get');
|
||||||
|
expect(commandNames).toContain('describe');
|
||||||
|
expect(commandNames).toContain('delete');
|
||||||
|
expect(commandNames).toContain('logs');
|
||||||
|
expect(commandNames).toContain('apply');
|
||||||
|
expect(commandNames).toContain('create');
|
||||||
|
expect(commandNames).toContain('edit');
|
||||||
|
expect(commandNames).toContain('setup');
|
||||||
|
expect(commandNames).toContain('claude');
|
||||||
|
expect(commandNames).toContain('project');
|
||||||
|
expect(commandNames).toContain('backup');
|
||||||
|
expect(commandNames).toContain('restore');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('instance command is removed (use get/delete/logs instead)', () => {
|
||||||
|
const program = createProgram();
|
||||||
|
const commandNames = program.commands.map((c) => c.name());
|
||||||
|
expect(commandNames).not.toContain('instance');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('claude command has config management subcommands', () => {
|
||||||
|
const program = createProgram();
|
||||||
|
const claude = program.commands.find((c) => c.name() === 'claude');
|
||||||
|
expect(claude).toBeDefined();
|
||||||
|
|
||||||
|
const subcommands = claude!.commands.map((c) => c.name());
|
||||||
|
expect(subcommands).toContain('generate');
|
||||||
|
expect(subcommands).toContain('show');
|
||||||
|
expect(subcommands).toContain('add');
|
||||||
|
expect(subcommands).toContain('remove');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('project command has action subcommands only', () => {
|
||||||
|
const program = createProgram();
|
||||||
|
const project = program.commands.find((c) => c.name() === 'project');
|
||||||
|
expect(project).toBeDefined();
|
||||||
|
|
||||||
|
const subcommands = project!.commands.map((c) => c.name());
|
||||||
|
expect(subcommands).toContain('profiles');
|
||||||
|
expect(subcommands).toContain('set-profiles');
|
||||||
|
// create is now top-level (mcpctl create project)
|
||||||
|
expect(subcommands).not.toContain('create');
|
||||||
|
expect(subcommands).not.toContain('list');
|
||||||
|
expect(subcommands).not.toContain('show');
|
||||||
|
expect(subcommands).not.toContain('delete');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('displays version', () => {
|
||||||
|
const program = createProgram();
|
||||||
|
expect(program.version()).toBeDefined();
|
||||||
|
expect(program.version()).toMatch(/^\d+\.\d+\.\d+$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('displays help without error', () => {
|
||||||
|
const program = createProgram();
|
||||||
|
const helpText = program.helpInformation();
|
||||||
|
expect(helpText).toContain('mcpctl');
|
||||||
|
expect(helpText).toContain('Manage MCP servers');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "Role" AS ENUM ('USER', 'ADMIN');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "Transport" AS ENUM ('STDIO', 'SSE', 'STREAMABLE_HTTP');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "InstanceStatus" AS ENUM ('STARTING', 'RUNNING', 'STOPPING', 'STOPPED', 'ERROR');
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "User" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"email" TEXT NOT NULL,
|
||||||
|
"name" TEXT,
|
||||||
|
"passwordHash" TEXT NOT NULL,
|
||||||
|
"role" "Role" NOT NULL DEFAULT 'USER',
|
||||||
|
"version" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Session" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"token" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "Session_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "McpServer" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"description" TEXT NOT NULL DEFAULT '',
|
||||||
|
"packageName" TEXT,
|
||||||
|
"dockerImage" TEXT,
|
||||||
|
"transport" "Transport" NOT NULL DEFAULT 'STDIO',
|
||||||
|
"repositoryUrl" TEXT,
|
||||||
|
"externalUrl" TEXT,
|
||||||
|
"command" JSONB,
|
||||||
|
"containerPort" INTEGER,
|
||||||
|
"envTemplate" JSONB NOT NULL DEFAULT '[]',
|
||||||
|
"version" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "McpServer_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "McpProfile" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"serverId" TEXT NOT NULL,
|
||||||
|
"permissions" JSONB NOT NULL DEFAULT '[]',
|
||||||
|
"envOverrides" JSONB NOT NULL DEFAULT '{}',
|
||||||
|
"version" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "McpProfile_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Project" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"description" TEXT NOT NULL DEFAULT '',
|
||||||
|
"ownerId" TEXT NOT NULL,
|
||||||
|
"version" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "Project_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "ProjectMcpProfile" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"projectId" TEXT NOT NULL,
|
||||||
|
"profileId" TEXT NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "ProjectMcpProfile_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "McpInstance" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"serverId" TEXT NOT NULL,
|
||||||
|
"containerId" TEXT,
|
||||||
|
"status" "InstanceStatus" NOT NULL DEFAULT 'STOPPED',
|
||||||
|
"port" INTEGER,
|
||||||
|
"metadata" JSONB NOT NULL DEFAULT '{}',
|
||||||
|
"version" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "McpInstance_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "AuditLog" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"action" TEXT NOT NULL,
|
||||||
|
"resource" TEXT NOT NULL,
|
||||||
|
"resourceId" TEXT,
|
||||||
|
"details" JSONB NOT NULL DEFAULT '{}',
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "User_email_idx" ON "User"("email");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "Session_token_key" ON "Session"("token");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Session_token_idx" ON "Session"("token");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Session_userId_idx" ON "Session"("userId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Session_expiresAt_idx" ON "Session"("expiresAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "McpServer_name_key" ON "McpServer"("name");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "McpServer_name_idx" ON "McpServer"("name");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "McpProfile_serverId_idx" ON "McpProfile"("serverId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "McpProfile_name_serverId_key" ON "McpProfile"("name", "serverId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "Project_name_key" ON "Project"("name");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Project_name_idx" ON "Project"("name");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Project_ownerId_idx" ON "Project"("ownerId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ProjectMcpProfile_projectId_idx" ON "ProjectMcpProfile"("projectId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "ProjectMcpProfile_profileId_idx" ON "ProjectMcpProfile"("profileId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "ProjectMcpProfile_projectId_profileId_key" ON "ProjectMcpProfile"("projectId", "profileId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "McpInstance_serverId_idx" ON "McpInstance"("serverId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "McpInstance_status_idx" ON "McpInstance"("status");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "AuditLog_userId_idx" ON "AuditLog"("userId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "AuditLog_action_idx" ON "AuditLog"("action");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "AuditLog_resource_idx" ON "AuditLog"("resource");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "AuditLog_createdAt_idx" ON "AuditLog"("createdAt");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Session" ADD CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "McpProfile" ADD CONSTRAINT "McpProfile_serverId_fkey" FOREIGN KEY ("serverId") REFERENCES "McpServer"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Project" ADD CONSTRAINT "Project_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ProjectMcpProfile" ADD CONSTRAINT "ProjectMcpProfile_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES "Project"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "ProjectMcpProfile" ADD CONSTRAINT "ProjectMcpProfile_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "McpProfile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "McpInstance" ADD CONSTRAINT "McpInstance_serverId_fkey" FOREIGN KEY ("serverId") REFERENCES "McpServer"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "AuditLog" ADD CONSTRAINT "AuditLog_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
3
src/db/prisma/migrations/migration_lock.toml
Normal file
3
src/db/prisma/migrations/migration_lock.toml
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (e.g., Git)
|
||||||
|
provider = "postgresql"
|
||||||
@@ -10,13 +10,14 @@ datasource db {
|
|||||||
// ── Users ──
|
// ── Users ──
|
||||||
|
|
||||||
model User {
|
model User {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
email String @unique
|
email String @unique
|
||||||
name String?
|
name String?
|
||||||
role Role @default(USER)
|
passwordHash String
|
||||||
version Int @default(1)
|
role Role @default(USER)
|
||||||
createdAt DateTime @default(now())
|
version Int @default(1)
|
||||||
updatedAt DateTime @updatedAt
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
sessions Session[]
|
sessions Session[]
|
||||||
auditLogs AuditLog[]
|
auditLogs AuditLog[]
|
||||||
@@ -56,6 +57,10 @@ model McpServer {
|
|||||||
dockerImage String?
|
dockerImage String?
|
||||||
transport Transport @default(STDIO)
|
transport Transport @default(STDIO)
|
||||||
repositoryUrl String?
|
repositoryUrl String?
|
||||||
|
externalUrl String?
|
||||||
|
command Json?
|
||||||
|
containerPort Int?
|
||||||
|
replicas Int @default(1)
|
||||||
envTemplate Json @default("[]")
|
envTemplate Json @default("[]")
|
||||||
version Int @default(1)
|
version Int @default(1)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
// Local LLM proxy entry point
|
|
||||||
// Will be implemented in Task 11
|
|
||||||
@@ -9,7 +9,7 @@
|
|||||||
"build": "tsc --build",
|
"build": "tsc --build",
|
||||||
"clean": "rimraf dist",
|
"clean": "rimraf dist",
|
||||||
"dev": "tsx watch src/index.ts",
|
"dev": "tsx watch src/index.ts",
|
||||||
"start": "node dist/index.js",
|
"start": "node dist/main.js",
|
||||||
"test": "vitest",
|
"test": "vitest",
|
||||||
"test:run": "vitest run"
|
"test:run": "vitest run"
|
||||||
},
|
},
|
||||||
@@ -20,11 +20,13 @@
|
|||||||
"@mcpctl/db": "workspace:*",
|
"@mcpctl/db": "workspace:*",
|
||||||
"@mcpctl/shared": "workspace:*",
|
"@mcpctl/shared": "workspace:*",
|
||||||
"@prisma/client": "^6.0.0",
|
"@prisma/client": "^6.0.0",
|
||||||
|
"bcrypt": "^5.1.1",
|
||||||
"dockerode": "^4.0.9",
|
"dockerode": "^4.0.9",
|
||||||
"fastify": "^5.0.0",
|
"fastify": "^5.0.0",
|
||||||
"zod": "^3.24.0"
|
"zod": "^3.24.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/bcrypt": "^5.0.2",
|
||||||
"@types/dockerode": "^4.0.1",
|
"@types/dockerode": "^4.0.1",
|
||||||
"@types/node": "^25.3.0"
|
"@types/node": "^25.3.0"
|
||||||
}
|
}
|
||||||
|
|||||||
117
src/mcpd/src/main.ts
Normal file
117
src/mcpd/src/main.ts
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import { seedMcpServers } from '@mcpctl/db';
|
||||||
|
import { loadConfigFromEnv } from './config/index.js';
|
||||||
|
import { createServer } from './server.js';
|
||||||
|
import { setupGracefulShutdown } from './utils/index.js';
|
||||||
|
import {
|
||||||
|
McpServerRepository,
|
||||||
|
McpProfileRepository,
|
||||||
|
McpInstanceRepository,
|
||||||
|
ProjectRepository,
|
||||||
|
AuditLogRepository,
|
||||||
|
} from './repositories/index.js';
|
||||||
|
import {
|
||||||
|
McpServerService,
|
||||||
|
McpProfileService,
|
||||||
|
InstanceService,
|
||||||
|
ProjectService,
|
||||||
|
AuditLogService,
|
||||||
|
DockerContainerManager,
|
||||||
|
MetricsCollector,
|
||||||
|
HealthAggregator,
|
||||||
|
BackupService,
|
||||||
|
RestoreService,
|
||||||
|
AuthService,
|
||||||
|
McpProxyService,
|
||||||
|
} from './services/index.js';
|
||||||
|
import {
|
||||||
|
registerMcpServerRoutes,
|
||||||
|
registerMcpProfileRoutes,
|
||||||
|
registerInstanceRoutes,
|
||||||
|
registerProjectRoutes,
|
||||||
|
registerAuditLogRoutes,
|
||||||
|
registerHealthMonitoringRoutes,
|
||||||
|
registerBackupRoutes,
|
||||||
|
registerAuthRoutes,
|
||||||
|
registerMcpProxyRoutes,
|
||||||
|
} from './routes/index.js';
|
||||||
|
|
||||||
|
async function main(): Promise<void> {
|
||||||
|
const config = loadConfigFromEnv();
|
||||||
|
|
||||||
|
// Database
|
||||||
|
const prisma = new PrismaClient({
|
||||||
|
datasources: { db: { url: config.databaseUrl } },
|
||||||
|
});
|
||||||
|
await prisma.$connect();
|
||||||
|
|
||||||
|
// Seed default servers (upsert, safe to repeat)
|
||||||
|
await seedMcpServers(prisma);
|
||||||
|
|
||||||
|
// Repositories
|
||||||
|
const serverRepo = new McpServerRepository(prisma);
|
||||||
|
const profileRepo = new McpProfileRepository(prisma);
|
||||||
|
const instanceRepo = new McpInstanceRepository(prisma);
|
||||||
|
const projectRepo = new ProjectRepository(prisma);
|
||||||
|
const auditLogRepo = new AuditLogRepository(prisma);
|
||||||
|
|
||||||
|
// Orchestrator
|
||||||
|
const orchestrator = new DockerContainerManager();
|
||||||
|
|
||||||
|
// Services
|
||||||
|
const serverService = new McpServerService(serverRepo);
|
||||||
|
const instanceService = new InstanceService(instanceRepo, serverRepo, orchestrator);
|
||||||
|
serverService.setInstanceService(instanceService);
|
||||||
|
const profileService = new McpProfileService(profileRepo, serverRepo);
|
||||||
|
const projectService = new ProjectService(projectRepo, profileRepo, serverRepo);
|
||||||
|
const auditLogService = new AuditLogService(auditLogRepo);
|
||||||
|
const metricsCollector = new MetricsCollector();
|
||||||
|
const healthAggregator = new HealthAggregator(metricsCollector, orchestrator);
|
||||||
|
const backupService = new BackupService(serverRepo, profileRepo, projectRepo);
|
||||||
|
const restoreService = new RestoreService(serverRepo, profileRepo, projectRepo);
|
||||||
|
const authService = new AuthService(prisma);
|
||||||
|
const mcpProxyService = new McpProxyService(instanceRepo, serverRepo);
|
||||||
|
|
||||||
|
// Server
|
||||||
|
const app = await createServer(config, {
|
||||||
|
health: {
|
||||||
|
checkDb: async () => {
|
||||||
|
try {
|
||||||
|
await prisma.$queryRaw`SELECT 1`;
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Routes
|
||||||
|
registerMcpServerRoutes(app, serverService, instanceService);
|
||||||
|
registerMcpProfileRoutes(app, profileService);
|
||||||
|
registerInstanceRoutes(app, instanceService);
|
||||||
|
registerProjectRoutes(app, projectService);
|
||||||
|
registerAuditLogRoutes(app, auditLogService);
|
||||||
|
registerHealthMonitoringRoutes(app, { healthAggregator, metricsCollector });
|
||||||
|
registerBackupRoutes(app, { backupService, restoreService });
|
||||||
|
registerAuthRoutes(app, { authService });
|
||||||
|
registerMcpProxyRoutes(app, {
|
||||||
|
mcpProxyService,
|
||||||
|
auditLogService,
|
||||||
|
authDeps: { findSession: (token) => authService.findSession(token) },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Start
|
||||||
|
await app.listen({ port: config.port, host: config.host });
|
||||||
|
app.log.info(`mcpd listening on ${config.host}:${config.port}`);
|
||||||
|
|
||||||
|
// Graceful shutdown
|
||||||
|
setupGracefulShutdown(app, {
|
||||||
|
disconnectDb: () => prisma.$disconnect(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((err) => {
|
||||||
|
console.error('Failed to start mcpd:', err);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
70
src/mcpd/src/repositories/audit-log.repository.ts
Normal file
70
src/mcpd/src/repositories/audit-log.repository.ts
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
import type { PrismaClient, AuditLog, Prisma } from '@prisma/client';
|
||||||
|
import type { IAuditLogRepository, AuditLogFilter } from './interfaces.js';
|
||||||
|
|
||||||
|
export class AuditLogRepository implements IAuditLogRepository {
|
||||||
|
constructor(private readonly prisma: PrismaClient) {}
|
||||||
|
|
||||||
|
async findAll(filter?: AuditLogFilter): Promise<AuditLog[]> {
|
||||||
|
const where = buildWhere(filter);
|
||||||
|
return this.prisma.auditLog.findMany({
|
||||||
|
where,
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
take: filter?.limit ?? 100,
|
||||||
|
skip: filter?.offset ?? 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async findById(id: string): Promise<AuditLog | null> {
|
||||||
|
return this.prisma.auditLog.findUnique({ where: { id } });
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(data: {
|
||||||
|
userId: string;
|
||||||
|
action: string;
|
||||||
|
resource: string;
|
||||||
|
resourceId?: string;
|
||||||
|
details?: Record<string, unknown>;
|
||||||
|
}): Promise<AuditLog> {
|
||||||
|
const createData: Prisma.AuditLogUncheckedCreateInput = {
|
||||||
|
userId: data.userId,
|
||||||
|
action: data.action,
|
||||||
|
resource: data.resource,
|
||||||
|
details: (data.details ?? {}) as Prisma.InputJsonValue,
|
||||||
|
};
|
||||||
|
if (data.resourceId !== undefined) {
|
||||||
|
createData.resourceId = data.resourceId;
|
||||||
|
}
|
||||||
|
return this.prisma.auditLog.create({ data: createData });
|
||||||
|
}
|
||||||
|
|
||||||
|
async count(filter?: AuditLogFilter): Promise<number> {
|
||||||
|
const where = buildWhere(filter);
|
||||||
|
return this.prisma.auditLog.count({ where });
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteOlderThan(date: Date): Promise<number> {
|
||||||
|
const result = await this.prisma.auditLog.deleteMany({
|
||||||
|
where: { createdAt: { lt: date } },
|
||||||
|
});
|
||||||
|
return result.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildWhere(filter?: AuditLogFilter): Prisma.AuditLogWhereInput {
|
||||||
|
const where: Prisma.AuditLogWhereInput = {};
|
||||||
|
if (!filter) return where;
|
||||||
|
|
||||||
|
if (filter.userId !== undefined) where.userId = filter.userId;
|
||||||
|
if (filter.action !== undefined) where.action = filter.action;
|
||||||
|
if (filter.resource !== undefined) where.resource = filter.resource;
|
||||||
|
if (filter.resourceId !== undefined) where.resourceId = filter.resourceId;
|
||||||
|
|
||||||
|
if (filter.since !== undefined || filter.until !== undefined) {
|
||||||
|
const createdAt: Prisma.DateTimeFilter = {};
|
||||||
|
if (filter.since !== undefined) createdAt.gte = filter.since;
|
||||||
|
if (filter.until !== undefined) createdAt.lte = filter.until;
|
||||||
|
where.createdAt = createdAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
return where;
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
export type { IMcpServerRepository, IMcpProfileRepository, IMcpInstanceRepository } from './interfaces.js';
|
export type { IMcpServerRepository, IMcpProfileRepository, IMcpInstanceRepository, IAuditLogRepository, AuditLogFilter } from './interfaces.js';
|
||||||
export { McpServerRepository } from './mcp-server.repository.js';
|
export { McpServerRepository } from './mcp-server.repository.js';
|
||||||
export { McpProfileRepository } from './mcp-profile.repository.js';
|
export { McpProfileRepository } from './mcp-profile.repository.js';
|
||||||
export type { IProjectRepository } from './project.repository.js';
|
export type { IProjectRepository } from './project.repository.js';
|
||||||
export { ProjectRepository } from './project.repository.js';
|
export { ProjectRepository } from './project.repository.js';
|
||||||
export { McpInstanceRepository } from './mcp-instance.repository.js';
|
export { McpInstanceRepository } from './mcp-instance.repository.js';
|
||||||
|
export { AuditLogRepository } from './audit-log.repository.js';
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { McpServer, McpProfile, McpInstance, InstanceStatus } from '@prisma/client';
|
import type { McpServer, McpProfile, McpInstance, AuditLog, InstanceStatus } from '@prisma/client';
|
||||||
import type { CreateMcpServerInput, UpdateMcpServerInput } from '../validation/mcp-server.schema.js';
|
import type { CreateMcpServerInput, UpdateMcpServerInput } from '../validation/mcp-server.schema.js';
|
||||||
import type { CreateMcpProfileInput, UpdateMcpProfileInput } from '../validation/mcp-profile.schema.js';
|
import type { CreateMcpProfileInput, UpdateMcpProfileInput } from '../validation/mcp-profile.schema.js';
|
||||||
|
|
||||||
@@ -28,3 +28,22 @@ export interface IMcpProfileRepository {
|
|||||||
update(id: string, data: UpdateMcpProfileInput): Promise<McpProfile>;
|
update(id: string, data: UpdateMcpProfileInput): Promise<McpProfile>;
|
||||||
delete(id: string): Promise<void>;
|
delete(id: string): Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface AuditLogFilter {
|
||||||
|
userId?: string;
|
||||||
|
action?: string;
|
||||||
|
resource?: string;
|
||||||
|
resourceId?: string;
|
||||||
|
since?: Date;
|
||||||
|
until?: Date;
|
||||||
|
limit?: number;
|
||||||
|
offset?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IAuditLogRepository {
|
||||||
|
findAll(filter?: AuditLogFilter): Promise<AuditLog[]>;
|
||||||
|
findById(id: string): Promise<AuditLog | null>;
|
||||||
|
create(data: { userId: string; action: string; resource: string; resourceId?: string; details?: Record<string, unknown> }): Promise<AuditLog>;
|
||||||
|
count(filter?: AuditLogFilter): Promise<number>;
|
||||||
|
deleteOlderThan(date: Date): Promise<number>;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { PrismaClient, McpServer } from '@prisma/client';
|
import { type PrismaClient, type McpServer, Prisma } from '@prisma/client';
|
||||||
import type { IMcpServerRepository } from './interfaces.js';
|
import type { IMcpServerRepository } from './interfaces.js';
|
||||||
import type { CreateMcpServerInput, UpdateMcpServerInput } from '../validation/mcp-server.schema.js';
|
import type { CreateMcpServerInput, UpdateMcpServerInput } from '../validation/mcp-server.schema.js';
|
||||||
|
|
||||||
@@ -26,6 +26,10 @@ export class McpServerRepository implements IMcpServerRepository {
|
|||||||
dockerImage: data.dockerImage ?? null,
|
dockerImage: data.dockerImage ?? null,
|
||||||
transport: data.transport,
|
transport: data.transport,
|
||||||
repositoryUrl: data.repositoryUrl ?? null,
|
repositoryUrl: data.repositoryUrl ?? null,
|
||||||
|
externalUrl: data.externalUrl ?? null,
|
||||||
|
command: data.command ?? Prisma.DbNull,
|
||||||
|
containerPort: data.containerPort ?? null,
|
||||||
|
replicas: data.replicas,
|
||||||
envTemplate: data.envTemplate,
|
envTemplate: data.envTemplate,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -38,6 +42,10 @@ export class McpServerRepository implements IMcpServerRepository {
|
|||||||
if (data.dockerImage !== undefined) updateData['dockerImage'] = data.dockerImage;
|
if (data.dockerImage !== undefined) updateData['dockerImage'] = data.dockerImage;
|
||||||
if (data.transport !== undefined) updateData['transport'] = data.transport;
|
if (data.transport !== undefined) updateData['transport'] = data.transport;
|
||||||
if (data.repositoryUrl !== undefined) updateData['repositoryUrl'] = data.repositoryUrl;
|
if (data.repositoryUrl !== undefined) updateData['repositoryUrl'] = data.repositoryUrl;
|
||||||
|
if (data.externalUrl !== undefined) updateData['externalUrl'] = data.externalUrl;
|
||||||
|
if (data.command !== undefined) updateData['command'] = data.command;
|
||||||
|
if (data.containerPort !== undefined) updateData['containerPort'] = data.containerPort;
|
||||||
|
if (data.replicas !== undefined) updateData['replicas'] = data.replicas;
|
||||||
if (data.envTemplate !== undefined) updateData['envTemplate'] = data.envTemplate;
|
if (data.envTemplate !== undefined) updateData['envTemplate'] = data.envTemplate;
|
||||||
|
|
||||||
return this.prisma.mcpServer.update({ where: { id }, data: updateData });
|
return this.prisma.mcpServer.update({ where: { id }, data: updateData });
|
||||||
|
|||||||
39
src/mcpd/src/routes/audit-logs.ts
Normal file
39
src/mcpd/src/routes/audit-logs.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import type { AuditLogService } from '../services/audit-log.service.js';
|
||||||
|
|
||||||
|
interface AuditLogQuery {
|
||||||
|
userId?: string;
|
||||||
|
action?: string;
|
||||||
|
resource?: string;
|
||||||
|
resourceId?: string;
|
||||||
|
since?: string;
|
||||||
|
until?: string;
|
||||||
|
limit?: string;
|
||||||
|
offset?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerAuditLogRoutes(app: FastifyInstance, service: AuditLogService): void {
|
||||||
|
app.get<{ Querystring: AuditLogQuery }>('/api/v1/audit-logs', async (request) => {
|
||||||
|
const q = request.query;
|
||||||
|
const params: Record<string, unknown> = {};
|
||||||
|
if (q.userId !== undefined) params.userId = q.userId;
|
||||||
|
if (q.action !== undefined) params.action = q.action;
|
||||||
|
if (q.resource !== undefined) params.resource = q.resource;
|
||||||
|
if (q.resourceId !== undefined) params.resourceId = q.resourceId;
|
||||||
|
if (q.since !== undefined) params.since = q.since;
|
||||||
|
if (q.until !== undefined) params.until = q.until;
|
||||||
|
if (q.limit !== undefined) params.limit = parseInt(q.limit, 10);
|
||||||
|
if (q.offset !== undefined) params.offset = parseInt(q.offset, 10);
|
||||||
|
return service.list(params);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get<{ Params: { id: string } }>('/api/v1/audit-logs/:id', async (request) => {
|
||||||
|
return service.getById(request.params.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/v1/audit-logs/purge', async (_request, reply) => {
|
||||||
|
const deleted = await service.purgeExpired();
|
||||||
|
reply.code(200);
|
||||||
|
return { deleted };
|
||||||
|
});
|
||||||
|
}
|
||||||
31
src/mcpd/src/routes/auth.ts
Normal file
31
src/mcpd/src/routes/auth.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import type { AuthService } from '../services/auth.service.js';
|
||||||
|
import { createAuthMiddleware } from '../middleware/auth.js';
|
||||||
|
|
||||||
|
export interface AuthRouteDeps {
|
||||||
|
authService: AuthService;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerAuthRoutes(app: FastifyInstance, deps: AuthRouteDeps): void {
|
||||||
|
const authMiddleware = createAuthMiddleware({
|
||||||
|
findSession: (token) => deps.authService.findSession(token),
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /api/v1/auth/login — no auth required
|
||||||
|
app.post<{
|
||||||
|
Body: { email: string; password: string };
|
||||||
|
}>('/api/v1/auth/login', async (request) => {
|
||||||
|
const { email, password } = request.body;
|
||||||
|
const result = await deps.authService.login(email, password);
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /api/v1/auth/logout — auth required
|
||||||
|
app.post('/api/v1/auth/logout', { preHandler: [authMiddleware] }, async (request) => {
|
||||||
|
const header = request.headers.authorization;
|
||||||
|
// Auth middleware already validated the header; extract the token
|
||||||
|
const token = header!.slice(7);
|
||||||
|
await deps.authService.logout(token);
|
||||||
|
return { success: true };
|
||||||
|
});
|
||||||
|
}
|
||||||
60
src/mcpd/src/routes/backup.ts
Normal file
60
src/mcpd/src/routes/backup.ts
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import type { BackupService } from '../services/backup/backup-service.js';
|
||||||
|
import type { RestoreService } from '../services/backup/restore-service.js';
|
||||||
|
import type { BackupBundle, BackupOptions } from '../services/backup/backup-service.js';
|
||||||
|
import type { ConflictStrategy, RestoreOptions } from '../services/backup/restore-service.js';
|
||||||
|
|
||||||
|
export interface BackupDeps {
|
||||||
|
backupService: BackupService;
|
||||||
|
restoreService: RestoreService;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerBackupRoutes(app: FastifyInstance, deps: BackupDeps): void {
|
||||||
|
app.post<{
|
||||||
|
Body: {
|
||||||
|
password?: string;
|
||||||
|
resources?: Array<'servers' | 'profiles' | 'projects'>;
|
||||||
|
};
|
||||||
|
}>('/api/v1/backup', async (request) => {
|
||||||
|
const opts: BackupOptions = {};
|
||||||
|
if (request.body?.password) {
|
||||||
|
opts.password = request.body.password;
|
||||||
|
}
|
||||||
|
if (request.body?.resources) {
|
||||||
|
opts.resources = request.body.resources;
|
||||||
|
}
|
||||||
|
const bundle = await deps.backupService.createBackup(opts);
|
||||||
|
return bundle;
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post<{
|
||||||
|
Body: {
|
||||||
|
bundle: BackupBundle;
|
||||||
|
password?: string;
|
||||||
|
conflictStrategy?: ConflictStrategy;
|
||||||
|
};
|
||||||
|
}>('/api/v1/restore', async (request, reply) => {
|
||||||
|
const { bundle, password, conflictStrategy } = request.body;
|
||||||
|
|
||||||
|
if (!deps.restoreService.validateBundle(bundle)) {
|
||||||
|
reply.code(400);
|
||||||
|
return { error: 'Invalid backup bundle format', statusCode: 400 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const restoreOpts: RestoreOptions = {};
|
||||||
|
if (password) {
|
||||||
|
restoreOpts.password = password;
|
||||||
|
}
|
||||||
|
if (conflictStrategy) {
|
||||||
|
restoreOpts.conflictStrategy = conflictStrategy;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await deps.restoreService.restore(bundle, restoreOpts);
|
||||||
|
|
||||||
|
if (result.errors.length > 0 && result.serversCreated === 0 && result.profilesCreated === 0 && result.projectsCreated === 0) {
|
||||||
|
reply.code(422);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
}
|
||||||
39
src/mcpd/src/routes/health-monitoring.ts
Normal file
39
src/mcpd/src/routes/health-monitoring.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import type { HealthAggregator } from '../services/health-aggregator.js';
|
||||||
|
import type { MetricsCollector } from '../services/metrics-collector.js';
|
||||||
|
|
||||||
|
export interface HealthMonitoringDeps {
|
||||||
|
healthAggregator: HealthAggregator;
|
||||||
|
metricsCollector: MetricsCollector;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerHealthMonitoringRoutes(app: FastifyInstance, deps: HealthMonitoringDeps): void {
|
||||||
|
app.get('/api/v1/health/overview', async () => {
|
||||||
|
return deps.healthAggregator.getOverview();
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get<{ Params: { id: string } }>('/api/v1/health/instances/:id', async (request, reply) => {
|
||||||
|
const health = deps.healthAggregator.getInstanceHealth(request.params.id);
|
||||||
|
if (!health) {
|
||||||
|
reply.code(404);
|
||||||
|
return { error: `Instance '${request.params.id}' not found`, statusCode: 404 };
|
||||||
|
}
|
||||||
|
return health;
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/v1/metrics', async () => {
|
||||||
|
const allMetrics = deps.metricsCollector.getAllMetrics();
|
||||||
|
return {
|
||||||
|
instances: allMetrics.map((m) => ({
|
||||||
|
instanceId: m.instanceId,
|
||||||
|
status: m.status,
|
||||||
|
uptime: m.uptime,
|
||||||
|
requestCount: m.requestCount,
|
||||||
|
errorCount: m.errorCount,
|
||||||
|
errorRate: m.requestCount > 0 ? m.errorCount / m.requestCount : 0,
|
||||||
|
lastRequestAt: m.lastRequestAt?.toISOString() ?? null,
|
||||||
|
})),
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -4,3 +4,12 @@ export { registerMcpServerRoutes } from './mcp-servers.js';
|
|||||||
export { registerMcpProfileRoutes } from './mcp-profiles.js';
|
export { registerMcpProfileRoutes } from './mcp-profiles.js';
|
||||||
export { registerProjectRoutes } from './projects.js';
|
export { registerProjectRoutes } from './projects.js';
|
||||||
export { registerInstanceRoutes } from './instances.js';
|
export { registerInstanceRoutes } from './instances.js';
|
||||||
|
export { registerAuditLogRoutes } from './audit-logs.js';
|
||||||
|
export { registerHealthMonitoringRoutes } from './health-monitoring.js';
|
||||||
|
export type { HealthMonitoringDeps } from './health-monitoring.js';
|
||||||
|
export { registerBackupRoutes } from './backup.js';
|
||||||
|
export type { BackupDeps } from './backup.js';
|
||||||
|
export { registerAuthRoutes } from './auth.js';
|
||||||
|
export type { AuthRouteDeps } from './auth.js';
|
||||||
|
export { registerMcpProxyRoutes } from './mcp-proxy.js';
|
||||||
|
export type { McpProxyRouteDeps } from './mcp-proxy.js';
|
||||||
|
|||||||
@@ -10,30 +10,15 @@ export function registerInstanceRoutes(app: FastifyInstance, service: InstanceSe
|
|||||||
return service.getById(request.params.id);
|
return service.getById(request.params.id);
|
||||||
});
|
});
|
||||||
|
|
||||||
app.post<{ Body: { serverId: string; env?: Record<string, string>; hostPort?: number } }>(
|
app.delete<{ Params: { id: string } }>('/api/v1/instances/:id', async (request, reply) => {
|
||||||
'/api/v1/instances',
|
const { serverId } = await service.remove(request.params.id);
|
||||||
async (request, reply) => {
|
// Reconcile: server will auto-create a replacement if replicas > 0
|
||||||
const { serverId } = request.body;
|
await service.reconcile(serverId);
|
||||||
const opts: { env?: Record<string, string>; hostPort?: number } = {};
|
reply.code(204);
|
||||||
if (request.body.env) {
|
|
||||||
opts.env = request.body.env;
|
|
||||||
}
|
|
||||||
if (request.body.hostPort !== undefined) {
|
|
||||||
opts.hostPort = request.body.hostPort;
|
|
||||||
}
|
|
||||||
const instance = await service.start(serverId, opts);
|
|
||||||
reply.code(201);
|
|
||||||
return instance;
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
app.post<{ Params: { id: string } }>('/api/v1/instances/:id/stop', async (request) => {
|
|
||||||
return service.stop(request.params.id);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
app.delete<{ Params: { id: string } }>('/api/v1/instances/:id', async (request, reply) => {
|
app.get<{ Params: { id: string } }>('/api/v1/instances/:id/inspect', async (request) => {
|
||||||
await service.remove(request.params.id);
|
return service.inspect(request.params.id);
|
||||||
reply.code(204);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
app.get<{ Params: { id: string }; Querystring: { tail?: string } }>(
|
app.get<{ Params: { id: string }; Querystring: { tail?: string } }>(
|
||||||
|
|||||||
37
src/mcpd/src/routes/mcp-proxy.ts
Normal file
37
src/mcpd/src/routes/mcp-proxy.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import type { McpProxyService } from '../services/mcp-proxy-service.js';
|
||||||
|
import type { AuditLogService } from '../services/audit-log.service.js';
|
||||||
|
import { createAuthMiddleware, type AuthDeps } from '../middleware/auth.js';
|
||||||
|
|
||||||
|
export interface McpProxyRouteDeps {
|
||||||
|
mcpProxyService: McpProxyService;
|
||||||
|
auditLogService: AuditLogService;
|
||||||
|
authDeps: AuthDeps;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerMcpProxyRoutes(app: FastifyInstance, deps: McpProxyRouteDeps): void {
|
||||||
|
const authMiddleware = createAuthMiddleware(deps.authDeps);
|
||||||
|
|
||||||
|
app.post<{
|
||||||
|
Body: {
|
||||||
|
serverId: string;
|
||||||
|
method: string;
|
||||||
|
params?: Record<string, unknown>;
|
||||||
|
};
|
||||||
|
}>('/api/v1/mcp/proxy', { preHandler: [authMiddleware] }, async (request) => {
|
||||||
|
const { serverId, method, params } = request.body;
|
||||||
|
|
||||||
|
const result = await deps.mcpProxyService.execute({ serverId, method, params });
|
||||||
|
|
||||||
|
// Log to audit with userId (set by auth middleware)
|
||||||
|
await deps.auditLogService.create({
|
||||||
|
userId: request.userId!,
|
||||||
|
action: 'MCP_PROXY',
|
||||||
|
resource: 'mcp-server',
|
||||||
|
resourceId: serverId,
|
||||||
|
details: { method, hasParams: params !== undefined },
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,7 +1,12 @@
|
|||||||
import type { FastifyInstance } from 'fastify';
|
import type { FastifyInstance } from 'fastify';
|
||||||
import type { McpServerService } from '../services/mcp-server.service.js';
|
import type { McpServerService } from '../services/mcp-server.service.js';
|
||||||
|
import type { InstanceService } from '../services/instance.service.js';
|
||||||
|
|
||||||
export function registerMcpServerRoutes(app: FastifyInstance, service: McpServerService): void {
|
export function registerMcpServerRoutes(
|
||||||
|
app: FastifyInstance,
|
||||||
|
service: McpServerService,
|
||||||
|
instanceService: InstanceService,
|
||||||
|
): void {
|
||||||
app.get('/api/v1/servers', async () => {
|
app.get('/api/v1/servers', async () => {
|
||||||
return service.list();
|
return service.list();
|
||||||
});
|
});
|
||||||
@@ -12,12 +17,17 @@ export function registerMcpServerRoutes(app: FastifyInstance, service: McpServer
|
|||||||
|
|
||||||
app.post('/api/v1/servers', async (request, reply) => {
|
app.post('/api/v1/servers', async (request, reply) => {
|
||||||
const server = await service.create(request.body);
|
const server = await service.create(request.body);
|
||||||
|
// Auto-reconcile: create instances to match replicas
|
||||||
|
await instanceService.reconcile(server.id);
|
||||||
reply.code(201);
|
reply.code(201);
|
||||||
return server;
|
return server;
|
||||||
});
|
});
|
||||||
|
|
||||||
app.put<{ Params: { id: string } }>('/api/v1/servers/:id', async (request) => {
|
app.put<{ Params: { id: string } }>('/api/v1/servers/:id', async (request) => {
|
||||||
return service.update(request.params.id, request.body);
|
const server = await service.update(request.params.id, request.body);
|
||||||
|
// Re-reconcile after update (replicas may have changed)
|
||||||
|
await instanceService.reconcile(server.id);
|
||||||
|
return server;
|
||||||
});
|
});
|
||||||
|
|
||||||
app.delete<{ Params: { id: string } }>('/api/v1/servers/:id', async (request, reply) => {
|
app.delete<{ Params: { id: string } }>('/api/v1/servers/:id', async (request, reply) => {
|
||||||
|
|||||||
17
src/mcpd/src/seed-runner.ts
Normal file
17
src/mcpd/src/seed-runner.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import { seedMcpServers } from '@mcpctl/db';
|
||||||
|
|
||||||
|
async function run(): Promise<void> {
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
try {
|
||||||
|
const count = await seedMcpServers(prisma);
|
||||||
|
console.log(`Seeded ${count} MCP servers`);
|
||||||
|
} finally {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
run().catch((err) => {
|
||||||
|
console.error('Seed failed:', err);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
73
src/mcpd/src/services/audit-log.service.ts
Normal file
73
src/mcpd/src/services/audit-log.service.ts
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import type { AuditLog } from '@prisma/client';
|
||||||
|
import type { IAuditLogRepository, AuditLogFilter } from '../repositories/interfaces.js';
|
||||||
|
import { NotFoundError } from './mcp-server.service.js';
|
||||||
|
|
||||||
|
export interface AuditLogQueryParams {
|
||||||
|
userId?: string;
|
||||||
|
action?: string;
|
||||||
|
resource?: string;
|
||||||
|
resourceId?: string;
|
||||||
|
since?: string;
|
||||||
|
until?: string;
|
||||||
|
limit?: number;
|
||||||
|
offset?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Default retention: 90 days */
|
||||||
|
const DEFAULT_RETENTION_DAYS = 90;
|
||||||
|
|
||||||
|
export class AuditLogService {
|
||||||
|
constructor(
|
||||||
|
private readonly repo: IAuditLogRepository,
|
||||||
|
private readonly retentionDays: number = DEFAULT_RETENTION_DAYS,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async list(params?: AuditLogQueryParams): Promise<{ logs: AuditLog[]; total: number }> {
|
||||||
|
const filter = this.buildFilter(params);
|
||||||
|
const [logs, total] = await Promise.all([
|
||||||
|
this.repo.findAll(filter),
|
||||||
|
this.repo.count(filter),
|
||||||
|
]);
|
||||||
|
return { logs, total };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getById(id: string): Promise<AuditLog> {
|
||||||
|
const log = await this.repo.findById(id);
|
||||||
|
if (!log) {
|
||||||
|
throw new NotFoundError(`Audit log '${id}' not found`);
|
||||||
|
}
|
||||||
|
return log;
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(data: {
|
||||||
|
userId: string;
|
||||||
|
action: string;
|
||||||
|
resource: string;
|
||||||
|
resourceId?: string;
|
||||||
|
details?: Record<string, unknown>;
|
||||||
|
}): Promise<AuditLog> {
|
||||||
|
return this.repo.create(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
async purgeExpired(): Promise<number> {
|
||||||
|
const cutoff = new Date();
|
||||||
|
cutoff.setDate(cutoff.getDate() - this.retentionDays);
|
||||||
|
return this.repo.deleteOlderThan(cutoff);
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildFilter(params?: AuditLogQueryParams): AuditLogFilter | undefined {
|
||||||
|
if (!params) return undefined;
|
||||||
|
const filter: AuditLogFilter = {};
|
||||||
|
|
||||||
|
if (params.userId !== undefined) filter.userId = params.userId;
|
||||||
|
if (params.action !== undefined) filter.action = params.action;
|
||||||
|
if (params.resource !== undefined) filter.resource = params.resource;
|
||||||
|
if (params.resourceId !== undefined) filter.resourceId = params.resourceId;
|
||||||
|
if (params.since !== undefined) filter.since = new Date(params.since);
|
||||||
|
if (params.until !== undefined) filter.until = new Date(params.until);
|
||||||
|
if (params.limit !== undefined) filter.limit = params.limit;
|
||||||
|
if (params.offset !== undefined) filter.offset = params.offset;
|
||||||
|
|
||||||
|
return filter;
|
||||||
|
}
|
||||||
|
}
|
||||||
66
src/mcpd/src/services/auth.service.ts
Normal file
66
src/mcpd/src/services/auth.service.ts
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import type { PrismaClient } from '@prisma/client';
|
||||||
|
import bcrypt from 'bcrypt';
|
||||||
|
|
||||||
|
/** 30 days in milliseconds */
|
||||||
|
const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
export interface LoginResult {
|
||||||
|
token: string;
|
||||||
|
expiresAt: Date;
|
||||||
|
user: { id: string; email: string; role: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
export class AuthenticationError extends Error {
|
||||||
|
readonly statusCode = 401;
|
||||||
|
constructor(message: string) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'AuthenticationError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class AuthService {
|
||||||
|
constructor(private readonly prisma: PrismaClient) {}
|
||||||
|
|
||||||
|
async login(email: string, password: string): Promise<LoginResult> {
|
||||||
|
const user = await this.prisma.user.findUnique({ where: { email } });
|
||||||
|
if (user === null) {
|
||||||
|
throw new AuthenticationError('Invalid email or password');
|
||||||
|
}
|
||||||
|
|
||||||
|
const valid = await bcrypt.compare(password, user.passwordHash);
|
||||||
|
if (!valid) {
|
||||||
|
throw new AuthenticationError('Invalid email or password');
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = randomUUID();
|
||||||
|
const expiresAt = new Date(Date.now() + SESSION_TTL_MS);
|
||||||
|
|
||||||
|
await this.prisma.session.create({
|
||||||
|
data: {
|
||||||
|
token,
|
||||||
|
userId: user.id,
|
||||||
|
expiresAt,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
token,
|
||||||
|
expiresAt,
|
||||||
|
user: { id: user.id, email: user.email, role: user.role },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async logout(token: string): Promise<void> {
|
||||||
|
// Delete the session by token; ignore if already deleted
|
||||||
|
await this.prisma.session.deleteMany({ where: { token } });
|
||||||
|
}
|
||||||
|
|
||||||
|
async findSession(token: string): Promise<{ userId: string; expiresAt: Date } | null> {
|
||||||
|
const session = await this.prisma.session.findUnique({ where: { token } });
|
||||||
|
if (session === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return { userId: session.userId, expiresAt: session.expiresAt };
|
||||||
|
}
|
||||||
|
}
|
||||||
143
src/mcpd/src/services/backup/backup-service.ts
Normal file
143
src/mcpd/src/services/backup/backup-service.ts
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
import type { IMcpServerRepository, IMcpProfileRepository } from '../../repositories/interfaces.js';
|
||||||
|
import type { IProjectRepository } from '../../repositories/project.repository.js';
|
||||||
|
import { encrypt, isSensitiveKey } from './crypto.js';
|
||||||
|
import type { EncryptedPayload } from './crypto.js';
|
||||||
|
import { APP_VERSION } from '@mcpctl/shared';
|
||||||
|
|
||||||
|
export interface BackupBundle {
|
||||||
|
version: string;
|
||||||
|
mcpctlVersion: string;
|
||||||
|
createdAt: string;
|
||||||
|
encrypted: boolean;
|
||||||
|
servers: BackupServer[];
|
||||||
|
profiles: BackupProfile[];
|
||||||
|
projects: BackupProject[];
|
||||||
|
encryptedSecrets?: EncryptedPayload;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BackupServer {
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
packageName: string | null;
|
||||||
|
dockerImage: string | null;
|
||||||
|
transport: string;
|
||||||
|
repositoryUrl: string | null;
|
||||||
|
envTemplate: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BackupProfile {
|
||||||
|
name: string;
|
||||||
|
serverName: string;
|
||||||
|
permissions: unknown;
|
||||||
|
envOverrides: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BackupProject {
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
profileNames: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BackupOptions {
|
||||||
|
password?: string;
|
||||||
|
resources?: Array<'servers' | 'profiles' | 'projects'>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BackupService {
|
||||||
|
constructor(
|
||||||
|
private serverRepo: IMcpServerRepository,
|
||||||
|
private profileRepo: IMcpProfileRepository,
|
||||||
|
private projectRepo: IProjectRepository,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async createBackup(options?: BackupOptions): Promise<BackupBundle> {
|
||||||
|
const resources = options?.resources ?? ['servers', 'profiles', 'projects'];
|
||||||
|
|
||||||
|
let servers: BackupServer[] = [];
|
||||||
|
let profiles: BackupProfile[] = [];
|
||||||
|
let projects: BackupProject[] = [];
|
||||||
|
|
||||||
|
if (resources.includes('servers')) {
|
||||||
|
const allServers = await this.serverRepo.findAll();
|
||||||
|
servers = allServers.map((s) => ({
|
||||||
|
name: s.name,
|
||||||
|
description: s.description,
|
||||||
|
packageName: s.packageName,
|
||||||
|
dockerImage: s.dockerImage,
|
||||||
|
transport: s.transport,
|
||||||
|
repositoryUrl: s.repositoryUrl,
|
||||||
|
envTemplate: s.envTemplate,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resources.includes('profiles')) {
|
||||||
|
const allProfiles = await this.profileRepo.findAll();
|
||||||
|
const serverMap = new Map<string, string>();
|
||||||
|
const allServers = await this.serverRepo.findAll();
|
||||||
|
for (const s of allServers) {
|
||||||
|
serverMap.set(s.id, s.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
profiles = allProfiles.map((p) => ({
|
||||||
|
name: p.name,
|
||||||
|
serverName: serverMap.get(p.serverId) ?? p.serverId,
|
||||||
|
permissions: p.permissions,
|
||||||
|
envOverrides: p.envOverrides,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resources.includes('projects')) {
|
||||||
|
const allProjects = await this.projectRepo.findAll();
|
||||||
|
const allProfiles = await this.profileRepo.findAll();
|
||||||
|
const profileMap = new Map<string, string>();
|
||||||
|
for (const p of allProfiles) {
|
||||||
|
profileMap.set(p.id, p.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
projects = await Promise.all(
|
||||||
|
allProjects.map(async (proj) => {
|
||||||
|
const profileIds = await this.projectRepo.getProfileIds(proj.id);
|
||||||
|
return {
|
||||||
|
name: proj.name,
|
||||||
|
description: proj.description,
|
||||||
|
profileNames: profileIds.map((id) => profileMap.get(id) ?? id),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const bundle: BackupBundle = {
|
||||||
|
version: '1',
|
||||||
|
mcpctlVersion: APP_VERSION,
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
encrypted: false,
|
||||||
|
servers,
|
||||||
|
profiles,
|
||||||
|
projects,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (options?.password) {
|
||||||
|
// Collect sensitive values and encrypt them
|
||||||
|
const secrets: Record<string, string> = {};
|
||||||
|
for (const profile of profiles) {
|
||||||
|
const overrides = profile.envOverrides as Record<string, string> | null;
|
||||||
|
if (overrides) {
|
||||||
|
for (const [key, value] of Object.entries(overrides)) {
|
||||||
|
if (isSensitiveKey(key)) {
|
||||||
|
const secretKey = `profile:${profile.name}:${key}`;
|
||||||
|
secrets[secretKey] = value;
|
||||||
|
(overrides as Record<string, string>)[key] = `__ENCRYPTED:${secretKey}__`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Object.keys(secrets).length > 0) {
|
||||||
|
bundle.encrypted = true;
|
||||||
|
bundle.encryptedSecrets = encrypt(JSON.stringify(secrets), options.password);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return bundle;
|
||||||
|
}
|
||||||
|
}
|
||||||
68
src/mcpd/src/services/backup/crypto.ts
Normal file
68
src/mcpd/src/services/backup/crypto.ts
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
import crypto from 'node:crypto';
|
||||||
|
|
||||||
|
const ALGORITHM = 'aes-256-gcm';
|
||||||
|
const KEY_LENGTH = 32;
|
||||||
|
const IV_LENGTH = 16;
|
||||||
|
const SALT_LENGTH = 32;
|
||||||
|
const AUTH_TAG_LENGTH = 16;
|
||||||
|
const SCRYPT_COST = 16384;
|
||||||
|
|
||||||
|
export interface EncryptedPayload {
|
||||||
|
algorithm: string;
|
||||||
|
salt: string;
|
||||||
|
iv: string;
|
||||||
|
authTag: string;
|
||||||
|
ciphertext: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deriveKey(password: string, salt: Buffer): Buffer {
|
||||||
|
return crypto.scryptSync(password, salt, KEY_LENGTH, { N: SCRYPT_COST });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function encrypt(data: string, password: string): EncryptedPayload {
|
||||||
|
const salt = crypto.randomBytes(SALT_LENGTH);
|
||||||
|
const key = deriveKey(password, salt);
|
||||||
|
const iv = crypto.randomBytes(IV_LENGTH);
|
||||||
|
|
||||||
|
const cipher = crypto.createCipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH });
|
||||||
|
const encrypted = Buffer.concat([cipher.update(data, 'utf-8'), cipher.final()]);
|
||||||
|
const authTag = cipher.getAuthTag();
|
||||||
|
|
||||||
|
return {
|
||||||
|
algorithm: ALGORITHM,
|
||||||
|
salt: salt.toString('base64'),
|
||||||
|
iv: iv.toString('base64'),
|
||||||
|
authTag: authTag.toString('base64'),
|
||||||
|
ciphertext: encrypted.toString('base64'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decrypt(payload: EncryptedPayload, password: string): string {
|
||||||
|
const salt = Buffer.from(payload.salt, 'base64');
|
||||||
|
const iv = Buffer.from(payload.iv, 'base64');
|
||||||
|
const authTag = Buffer.from(payload.authTag, 'base64');
|
||||||
|
const ciphertext = Buffer.from(payload.ciphertext, 'base64');
|
||||||
|
|
||||||
|
const key = deriveKey(password, salt);
|
||||||
|
|
||||||
|
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH });
|
||||||
|
decipher.setAuthTag(authTag);
|
||||||
|
|
||||||
|
const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
||||||
|
return decrypted.toString('utf-8');
|
||||||
|
}
|
||||||
|
|
||||||
|
const SENSITIVE_PATTERNS = [
|
||||||
|
/_KEY$/i,
|
||||||
|
/_SECRET$/i,
|
||||||
|
/_TOKEN$/i,
|
||||||
|
/PASSWORD/i,
|
||||||
|
/^API_KEY$/i,
|
||||||
|
/^SECRET$/i,
|
||||||
|
/^TOKEN$/i,
|
||||||
|
/^CREDENTIALS$/i,
|
||||||
|
];
|
||||||
|
|
||||||
|
export function isSensitiveKey(key: string): boolean {
|
||||||
|
return SENSITIVE_PATTERNS.some((p) => p.test(key));
|
||||||
|
}
|
||||||
6
src/mcpd/src/services/backup/index.ts
Normal file
6
src/mcpd/src/services/backup/index.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
export { BackupService } from './backup-service.js';
|
||||||
|
export type { BackupBundle, BackupServer, BackupProfile, BackupProject, BackupOptions } from './backup-service.js';
|
||||||
|
export { RestoreService } from './restore-service.js';
|
||||||
|
export type { RestoreOptions, RestoreResult, ConflictStrategy } from './restore-service.js';
|
||||||
|
export { encrypt, decrypt, isSensitiveKey } from './crypto.js';
|
||||||
|
export type { EncryptedPayload } from './crypto.js';
|
||||||
225
src/mcpd/src/services/backup/restore-service.ts
Normal file
225
src/mcpd/src/services/backup/restore-service.ts
Normal file
@@ -0,0 +1,225 @@
|
|||||||
|
import type { IMcpServerRepository, IMcpProfileRepository } from '../../repositories/interfaces.js';
|
||||||
|
import type { IProjectRepository } from '../../repositories/project.repository.js';
|
||||||
|
import { decrypt } from './crypto.js';
|
||||||
|
import type { BackupBundle } from './backup-service.js';
|
||||||
|
|
||||||
|
export type ConflictStrategy = 'skip' | 'overwrite' | 'fail';
|
||||||
|
|
||||||
|
export interface RestoreOptions {
|
||||||
|
password?: string;
|
||||||
|
conflictStrategy?: ConflictStrategy;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RestoreResult {
|
||||||
|
serversCreated: number;
|
||||||
|
serversSkipped: number;
|
||||||
|
profilesCreated: number;
|
||||||
|
profilesSkipped: number;
|
||||||
|
projectsCreated: number;
|
||||||
|
projectsSkipped: number;
|
||||||
|
errors: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RestoreService {
|
||||||
|
constructor(
|
||||||
|
private serverRepo: IMcpServerRepository,
|
||||||
|
private profileRepo: IMcpProfileRepository,
|
||||||
|
private projectRepo: IProjectRepository,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
validateBundle(bundle: unknown): bundle is BackupBundle {
|
||||||
|
if (typeof bundle !== 'object' || bundle === null) return false;
|
||||||
|
const b = bundle as Record<string, unknown>;
|
||||||
|
return (
|
||||||
|
typeof b['version'] === 'string' &&
|
||||||
|
Array.isArray(b['servers']) &&
|
||||||
|
Array.isArray(b['profiles']) &&
|
||||||
|
Array.isArray(b['projects'])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async restore(bundle: BackupBundle, options?: RestoreOptions): Promise<RestoreResult> {
|
||||||
|
const strategy = options?.conflictStrategy ?? 'skip';
|
||||||
|
const result: RestoreResult = {
|
||||||
|
serversCreated: 0,
|
||||||
|
serversSkipped: 0,
|
||||||
|
profilesCreated: 0,
|
||||||
|
profilesSkipped: 0,
|
||||||
|
projectsCreated: 0,
|
||||||
|
projectsSkipped: 0,
|
||||||
|
errors: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
// Decrypt secrets if encrypted
|
||||||
|
let secrets: Record<string, string> = {};
|
||||||
|
if (bundle.encrypted && bundle.encryptedSecrets) {
|
||||||
|
if (!options?.password) {
|
||||||
|
result.errors.push('Backup is encrypted but no password provided');
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
secrets = JSON.parse(decrypt(bundle.encryptedSecrets, options.password)) as Record<string, string>;
|
||||||
|
} catch {
|
||||||
|
result.errors.push('Failed to decrypt backup - incorrect password or corrupted data');
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restore secrets into profile envOverrides
|
||||||
|
for (const profile of bundle.profiles) {
|
||||||
|
const overrides = profile.envOverrides as Record<string, string> | null;
|
||||||
|
if (overrides) {
|
||||||
|
for (const [key, value] of Object.entries(overrides)) {
|
||||||
|
if (typeof value === 'string' && value.startsWith('__ENCRYPTED:') && value.endsWith('__')) {
|
||||||
|
const secretKey = value.slice(12, -2);
|
||||||
|
const decrypted = secrets[secretKey];
|
||||||
|
if (decrypted !== undefined) {
|
||||||
|
overrides[key] = decrypted;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restore servers
|
||||||
|
const serverNameToId = new Map<string, string>();
|
||||||
|
for (const server of bundle.servers) {
|
||||||
|
try {
|
||||||
|
const existing = await this.serverRepo.findByName(server.name);
|
||||||
|
if (existing) {
|
||||||
|
if (strategy === 'fail') {
|
||||||
|
result.errors.push(`Server "${server.name}" already exists`);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (strategy === 'skip') {
|
||||||
|
result.serversSkipped++;
|
||||||
|
serverNameToId.set(server.name, existing.id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// overwrite
|
||||||
|
const updateData: Parameters<IMcpServerRepository['update']>[1] = {
|
||||||
|
description: server.description,
|
||||||
|
transport: server.transport as 'STDIO' | 'SSE' | 'STREAMABLE_HTTP',
|
||||||
|
};
|
||||||
|
if (server.packageName) updateData.packageName = server.packageName;
|
||||||
|
if (server.dockerImage) updateData.dockerImage = server.dockerImage;
|
||||||
|
if (server.repositoryUrl) updateData.repositoryUrl = server.repositoryUrl;
|
||||||
|
await this.serverRepo.update(existing.id, updateData);
|
||||||
|
serverNameToId.set(server.name, existing.id);
|
||||||
|
result.serversCreated++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const createData: Parameters<IMcpServerRepository['create']>[0] = {
|
||||||
|
name: server.name,
|
||||||
|
description: server.description,
|
||||||
|
transport: server.transport as 'STDIO' | 'SSE' | 'STREAMABLE_HTTP',
|
||||||
|
replicas: (server as { replicas?: number }).replicas ?? 1,
|
||||||
|
envTemplate: (server.envTemplate ?? []) as Array<{ name: string; description: string; isSecret: boolean }>,
|
||||||
|
};
|
||||||
|
if (server.packageName) createData.packageName = server.packageName;
|
||||||
|
if (server.dockerImage) createData.dockerImage = server.dockerImage;
|
||||||
|
if (server.repositoryUrl) createData.repositoryUrl = server.repositoryUrl;
|
||||||
|
const created = await this.serverRepo.create(createData);
|
||||||
|
serverNameToId.set(server.name, created.id);
|
||||||
|
result.serversCreated++;
|
||||||
|
} catch (err) {
|
||||||
|
result.errors.push(`Failed to restore server "${server.name}": ${err instanceof Error ? err.message : String(err)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restore profiles
|
||||||
|
const profileNameToId = new Map<string, string>();
|
||||||
|
for (const profile of bundle.profiles) {
|
||||||
|
try {
|
||||||
|
const serverId = serverNameToId.get(profile.serverName);
|
||||||
|
if (!serverId) {
|
||||||
|
// Try to find server by name in DB
|
||||||
|
const server = await this.serverRepo.findByName(profile.serverName);
|
||||||
|
if (!server) {
|
||||||
|
result.errors.push(`Profile "${profile.name}" references unknown server "${profile.serverName}"`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
serverNameToId.set(profile.serverName, server.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sid = serverNameToId.get(profile.serverName)!;
|
||||||
|
const existing = await this.profileRepo.findByServerAndName(sid, profile.name);
|
||||||
|
if (existing) {
|
||||||
|
if (strategy === 'fail') {
|
||||||
|
result.errors.push(`Profile "${profile.name}" already exists for server "${profile.serverName}"`);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (strategy === 'skip') {
|
||||||
|
result.profilesSkipped++;
|
||||||
|
profileNameToId.set(profile.name, existing.id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// overwrite
|
||||||
|
await this.profileRepo.update(existing.id, {
|
||||||
|
permissions: profile.permissions as string[],
|
||||||
|
envOverrides: profile.envOverrides as Record<string, string>,
|
||||||
|
});
|
||||||
|
profileNameToId.set(profile.name, existing.id);
|
||||||
|
result.profilesCreated++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const created = await this.profileRepo.create({
|
||||||
|
name: profile.name,
|
||||||
|
serverId: sid,
|
||||||
|
permissions: profile.permissions as string[],
|
||||||
|
envOverrides: profile.envOverrides as Record<string, string>,
|
||||||
|
});
|
||||||
|
profileNameToId.set(profile.name, created.id);
|
||||||
|
result.profilesCreated++;
|
||||||
|
} catch (err) {
|
||||||
|
result.errors.push(`Failed to restore profile "${profile.name}": ${err instanceof Error ? err.message : String(err)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restore projects
|
||||||
|
for (const project of bundle.projects) {
|
||||||
|
try {
|
||||||
|
const existing = await this.projectRepo.findByName(project.name);
|
||||||
|
if (existing) {
|
||||||
|
if (strategy === 'fail') {
|
||||||
|
result.errors.push(`Project "${project.name}" already exists`);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (strategy === 'skip') {
|
||||||
|
result.projectsSkipped++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// overwrite - update and set profiles
|
||||||
|
await this.projectRepo.update(existing.id, { description: project.description });
|
||||||
|
const profileIds = project.profileNames
|
||||||
|
.map((name) => profileNameToId.get(name))
|
||||||
|
.filter((id): id is string => id !== undefined);
|
||||||
|
if (profileIds.length > 0) {
|
||||||
|
await this.projectRepo.setProfiles(existing.id, profileIds);
|
||||||
|
}
|
||||||
|
result.projectsCreated++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const created = await this.projectRepo.create({
|
||||||
|
name: project.name,
|
||||||
|
description: project.description,
|
||||||
|
ownerId: 'system',
|
||||||
|
});
|
||||||
|
const profileIds = project.profileNames
|
||||||
|
.map((name) => profileNameToId.get(name))
|
||||||
|
.filter((id): id is string => id !== undefined);
|
||||||
|
if (profileIds.length > 0) {
|
||||||
|
await this.projectRepo.setProfiles(created.id, profileIds);
|
||||||
|
}
|
||||||
|
result.projectsCreated++;
|
||||||
|
} catch (err) {
|
||||||
|
result.errors.push(`Failed to restore project "${project.name}": ${err instanceof Error ? err.message : String(err)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -74,7 +74,7 @@ export class DockerContainerManager implements McpOrchestrator {
|
|||||||
? Object.entries(spec.env).map(([k, v]) => `${k}=${v}`)
|
? Object.entries(spec.env).map(([k, v]) => `${k}=${v}`)
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
const container = await this.docker.createContainer({
|
const createOpts: Docker.ContainerCreateOptions = {
|
||||||
Image: spec.image,
|
Image: spec.image,
|
||||||
name: spec.name,
|
name: spec.name,
|
||||||
Env: envArr,
|
Env: envArr,
|
||||||
@@ -86,7 +86,12 @@ export class DockerContainerManager implements McpOrchestrator {
|
|||||||
NanoCpus: nanoCpus,
|
NanoCpus: nanoCpus,
|
||||||
NetworkMode: spec.network ?? 'bridge',
|
NetworkMode: spec.network ?? 'bridge',
|
||||||
},
|
},
|
||||||
});
|
};
|
||||||
|
if (spec.command) {
|
||||||
|
createOpts.Cmd = spec.command;
|
||||||
|
}
|
||||||
|
|
||||||
|
const container = await this.docker.createContainer(createOpts);
|
||||||
|
|
||||||
await container.start();
|
await container.start();
|
||||||
|
|
||||||
|
|||||||
99
src/mcpd/src/services/health-aggregator.ts
Normal file
99
src/mcpd/src/services/health-aggregator.ts
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
import type { MetricsCollector, InstanceMetrics } from './metrics-collector.js';
|
||||||
|
import type { McpOrchestrator } from './orchestrator.js';
|
||||||
|
|
||||||
|
export interface SystemHealth {
|
||||||
|
overallStatus: 'healthy' | 'degraded' | 'unhealthy';
|
||||||
|
totalInstances: number;
|
||||||
|
healthyCount: number;
|
||||||
|
unhealthyCount: number;
|
||||||
|
unknownCount: number;
|
||||||
|
runtimeAvailable: boolean;
|
||||||
|
aggregateErrorRate: number;
|
||||||
|
averageUptime: number;
|
||||||
|
timestamp: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InstanceHealth {
|
||||||
|
instanceId: string;
|
||||||
|
status: InstanceMetrics['status'];
|
||||||
|
uptime: number;
|
||||||
|
requestCount: number;
|
||||||
|
errorCount: number;
|
||||||
|
errorRate: number;
|
||||||
|
averageLatencyMs: number;
|
||||||
|
lastRequestAt: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class HealthAggregator {
|
||||||
|
constructor(
|
||||||
|
private metricsCollector: MetricsCollector,
|
||||||
|
private orchestrator: McpOrchestrator,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async getOverview(): Promise<SystemHealth> {
|
||||||
|
const runtimeAvailable = await this.orchestrator.ping().catch(() => false);
|
||||||
|
const allMetrics = this.metricsCollector.getAllMetrics();
|
||||||
|
|
||||||
|
let healthyCount = 0;
|
||||||
|
let unhealthyCount = 0;
|
||||||
|
let unknownCount = 0;
|
||||||
|
let totalErrors = 0;
|
||||||
|
let totalRequests = 0;
|
||||||
|
let totalUptime = 0;
|
||||||
|
|
||||||
|
for (const m of allMetrics) {
|
||||||
|
switch (m.status) {
|
||||||
|
case 'healthy':
|
||||||
|
healthyCount++;
|
||||||
|
break;
|
||||||
|
case 'unhealthy':
|
||||||
|
unhealthyCount++;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
unknownCount++;
|
||||||
|
}
|
||||||
|
totalErrors += m.errorCount;
|
||||||
|
totalRequests += m.requestCount;
|
||||||
|
totalUptime += m.uptime;
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalInstances = allMetrics.length;
|
||||||
|
const aggregateErrorRate = totalRequests > 0 ? totalErrors / totalRequests : 0;
|
||||||
|
const averageUptime = totalInstances > 0 ? totalUptime / totalInstances : 0;
|
||||||
|
|
||||||
|
let overallStatus: SystemHealth['overallStatus'] = 'healthy';
|
||||||
|
if (!runtimeAvailable || (totalInstances > 0 && unhealthyCount === totalInstances)) {
|
||||||
|
overallStatus = 'unhealthy';
|
||||||
|
} else if (unhealthyCount > 0 || unknownCount > 0) {
|
||||||
|
overallStatus = 'degraded';
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
overallStatus,
|
||||||
|
totalInstances,
|
||||||
|
healthyCount,
|
||||||
|
unhealthyCount,
|
||||||
|
unknownCount,
|
||||||
|
runtimeAvailable,
|
||||||
|
aggregateErrorRate,
|
||||||
|
averageUptime,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
getInstanceHealth(instanceId: string): InstanceHealth | undefined {
|
||||||
|
const m = this.metricsCollector.getMetrics(instanceId);
|
||||||
|
if (!m) return undefined;
|
||||||
|
|
||||||
|
return {
|
||||||
|
instanceId: m.instanceId,
|
||||||
|
status: m.status,
|
||||||
|
uptime: m.uptime,
|
||||||
|
requestCount: m.requestCount,
|
||||||
|
errorCount: m.errorCount,
|
||||||
|
errorRate: this.metricsCollector.getErrorRate(instanceId),
|
||||||
|
averageLatencyMs: this.metricsCollector.getAverageLatency(instanceId),
|
||||||
|
lastRequestAt: m.lastRequestAt?.toISOString() ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,25 @@
|
|||||||
export { McpServerService, NotFoundError, ConflictError } from './mcp-server.service.js';
|
export { McpServerService, NotFoundError, ConflictError } from './mcp-server.service.js';
|
||||||
export { McpProfileService } from './mcp-profile.service.js';
|
export { McpProfileService } from './mcp-profile.service.js';
|
||||||
export { ProjectService } from './project.service.js';
|
export { ProjectService } from './project.service.js';
|
||||||
export { InstanceService } from './instance.service.js';
|
export { InstanceService, InvalidStateError } from './instance.service.js';
|
||||||
export { generateMcpConfig } from './mcp-config-generator.js';
|
export { generateMcpConfig } from './mcp-config-generator.js';
|
||||||
export type { McpConfig, McpConfigServer, ProfileWithServer } from './mcp-config-generator.js';
|
export type { McpConfig, McpConfigServer, ProfileWithServer } from './mcp-config-generator.js';
|
||||||
export type { McpOrchestrator, ContainerSpec, ContainerInfo, ContainerLogs } from './orchestrator.js';
|
export type { McpOrchestrator, ContainerSpec, ContainerInfo, ContainerLogs } from './orchestrator.js';
|
||||||
export { DEFAULT_MEMORY_LIMIT, DEFAULT_NANO_CPUS } from './orchestrator.js';
|
export { DEFAULT_MEMORY_LIMIT, DEFAULT_NANO_CPUS } from './orchestrator.js';
|
||||||
export { DockerContainerManager } from './docker/container-manager.js';
|
export { DockerContainerManager } from './docker/container-manager.js';
|
||||||
|
export { AuditLogService } from './audit-log.service.js';
|
||||||
|
export type { AuditLogQueryParams } from './audit-log.service.js';
|
||||||
|
export { KubernetesOrchestrator } from './k8s/index.js';
|
||||||
|
export type { K8sClientConfig } from './k8s/index.js';
|
||||||
|
export { MetricsCollector } from './metrics-collector.js';
|
||||||
|
export type { InstanceMetrics } from './metrics-collector.js';
|
||||||
|
export { HealthAggregator } from './health-aggregator.js';
|
||||||
|
export type { SystemHealth, InstanceHealth } from './health-aggregator.js';
|
||||||
|
export { BackupService } from './backup/index.js';
|
||||||
|
export type { BackupBundle, BackupOptions } from './backup/index.js';
|
||||||
|
export { RestoreService } from './backup/index.js';
|
||||||
|
export type { RestoreOptions, RestoreResult, ConflictStrategy } from './backup/index.js';
|
||||||
|
export { AuthService, AuthenticationError } from './auth.service.js';
|
||||||
|
export type { LoginResult } from './auth.service.js';
|
||||||
|
export { McpProxyService } from './mcp-proxy-service.js';
|
||||||
|
export type { McpProxyRequest, McpProxyResponse } from './mcp-proxy-service.js';
|
||||||
|
|||||||
@@ -1,8 +1,16 @@
|
|||||||
import type { McpInstance } from '@prisma/client';
|
import type { McpInstance } from '@prisma/client';
|
||||||
import type { IMcpInstanceRepository, IMcpServerRepository } from '../repositories/interfaces.js';
|
import type { IMcpInstanceRepository, IMcpServerRepository } from '../repositories/interfaces.js';
|
||||||
import type { McpOrchestrator, ContainerSpec } from './orchestrator.js';
|
import type { McpOrchestrator, ContainerSpec, ContainerInfo } from './orchestrator.js';
|
||||||
import { NotFoundError } from './mcp-server.service.js';
|
import { NotFoundError } from './mcp-server.service.js';
|
||||||
|
|
||||||
|
export class InvalidStateError extends Error {
|
||||||
|
readonly statusCode = 409;
|
||||||
|
constructor(message: string) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'InvalidStateError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export class InstanceService {
|
export class InstanceService {
|
||||||
constructor(
|
constructor(
|
||||||
private instanceRepo: IMcpInstanceRepository,
|
private instanceRepo: IMcpInstanceRepository,
|
||||||
@@ -20,13 +28,117 @@ export class InstanceService {
|
|||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
async start(serverId: string, opts?: { env?: Record<string, string>; hostPort?: number }): Promise<McpInstance> {
|
/**
|
||||||
|
* Reconcile instances for a server to match desired replica count.
|
||||||
|
* - If fewer running instances than replicas: start new ones
|
||||||
|
* - If more running instances than replicas: remove excess (oldest first)
|
||||||
|
*/
|
||||||
|
async reconcile(serverId: string): Promise<McpInstance[]> {
|
||||||
const server = await this.serverRepo.findById(serverId);
|
const server = await this.serverRepo.findById(serverId);
|
||||||
if (!server) throw new NotFoundError(`McpServer '${serverId}' not found`);
|
if (!server) throw new NotFoundError(`McpServer '${serverId}' not found`);
|
||||||
|
|
||||||
|
const instances = await this.instanceRepo.findAll(serverId);
|
||||||
|
const active = instances.filter((i) => i.status === 'RUNNING' || i.status === 'STARTING');
|
||||||
|
const desired = server.replicas;
|
||||||
|
|
||||||
|
if (active.length < desired) {
|
||||||
|
// Scale up
|
||||||
|
const toStart = desired - active.length;
|
||||||
|
for (let i = 0; i < toStart; i++) {
|
||||||
|
await this.startOne(serverId);
|
||||||
|
}
|
||||||
|
} else if (active.length > desired) {
|
||||||
|
// Scale down — remove oldest first
|
||||||
|
const excess = active
|
||||||
|
.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())
|
||||||
|
.slice(0, active.length - desired);
|
||||||
|
for (const inst of excess) {
|
||||||
|
await this.removeOne(inst);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.instanceRepo.findAll(serverId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove an instance (stop container + delete DB record).
|
||||||
|
* Does NOT reconcile — caller should reconcile after if needed.
|
||||||
|
*/
|
||||||
|
async remove(id: string): Promise<{ serverId: string }> {
|
||||||
|
const instance = await this.getById(id);
|
||||||
|
|
||||||
|
if (instance.containerId) {
|
||||||
|
try {
|
||||||
|
await this.orchestrator.stopContainer(instance.containerId);
|
||||||
|
} catch {
|
||||||
|
// Container may already be stopped
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await this.orchestrator.removeContainer(instance.containerId, true);
|
||||||
|
} catch {
|
||||||
|
// Container may already be gone
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.instanceRepo.delete(id);
|
||||||
|
return { serverId: instance.serverId };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove all instances for a server (used before server deletion).
|
||||||
|
* Stops all containers so Prisma cascade only cleans up DB records.
|
||||||
|
*/
|
||||||
|
async removeAllForServer(serverId: string): Promise<void> {
|
||||||
|
const instances = await this.instanceRepo.findAll(serverId);
|
||||||
|
for (const inst of instances) {
|
||||||
|
if (inst.containerId) {
|
||||||
|
try {
|
||||||
|
await this.orchestrator.stopContainer(inst.containerId);
|
||||||
|
} catch {
|
||||||
|
// best-effort
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await this.orchestrator.removeContainer(inst.containerId, true);
|
||||||
|
} catch {
|
||||||
|
// best-effort
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async inspect(id: string): Promise<ContainerInfo> {
|
||||||
|
const instance = await this.getById(id);
|
||||||
|
if (!instance.containerId) {
|
||||||
|
throw new InvalidStateError(`Instance '${id}' has no container`);
|
||||||
|
}
|
||||||
|
return this.orchestrator.inspectContainer(instance.containerId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getLogs(id: string, opts?: { tail?: number }): Promise<{ stdout: string; stderr: string }> {
|
||||||
|
const instance = await this.getById(id);
|
||||||
|
if (!instance.containerId) {
|
||||||
|
return { stdout: '', stderr: '' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.orchestrator.getContainerLogs(instance.containerId, opts);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Start a single instance for a server. */
|
||||||
|
private async startOne(serverId: string): Promise<McpInstance> {
|
||||||
|
const server = await this.serverRepo.findById(serverId);
|
||||||
|
if (!server) throw new NotFoundError(`McpServer '${serverId}' not found`);
|
||||||
|
|
||||||
|
// External servers don't need container management
|
||||||
|
if (server.externalUrl) {
|
||||||
|
return this.instanceRepo.create({
|
||||||
|
serverId,
|
||||||
|
status: 'RUNNING',
|
||||||
|
metadata: { external: true, url: server.externalUrl },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const image = server.dockerImage ?? server.packageName ?? server.name;
|
const image = server.dockerImage ?? server.packageName ?? server.name;
|
||||||
|
|
||||||
// Create DB record first in STARTING state
|
|
||||||
let instance = await this.instanceRepo.create({
|
let instance = await this.instanceRepo.create({
|
||||||
serverId,
|
serverId,
|
||||||
status: 'STARTING',
|
status: 'STARTING',
|
||||||
@@ -36,17 +148,18 @@ export class InstanceService {
|
|||||||
const spec: ContainerSpec = {
|
const spec: ContainerSpec = {
|
||||||
image,
|
image,
|
||||||
name: `mcpctl-${server.name}-${instance.id}`,
|
name: `mcpctl-${server.name}-${instance.id}`,
|
||||||
hostPort: opts?.hostPort ?? null,
|
hostPort: null,
|
||||||
labels: {
|
labels: {
|
||||||
'mcpctl.server-id': serverId,
|
'mcpctl.server-id': serverId,
|
||||||
'mcpctl.instance-id': instance.id,
|
'mcpctl.instance-id': instance.id,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
if (server.transport === 'SSE' || server.transport === 'STREAMABLE_HTTP') {
|
if (server.transport === 'SSE' || server.transport === 'STREAMABLE_HTTP') {
|
||||||
spec.containerPort = 3000;
|
spec.containerPort = server.containerPort ?? 3000;
|
||||||
}
|
}
|
||||||
if (opts?.env) {
|
const command = server.command as string[] | null;
|
||||||
spec.env = opts.env;
|
if (command) {
|
||||||
|
spec.command = command;
|
||||||
}
|
}
|
||||||
|
|
||||||
const containerInfo = await this.orchestrator.createContainer(spec);
|
const containerInfo = await this.orchestrator.createContainer(spec);
|
||||||
@@ -60,7 +173,6 @@ export class InstanceService {
|
|||||||
|
|
||||||
instance = await this.instanceRepo.updateStatus(instance.id, 'RUNNING', updateFields);
|
instance = await this.instanceRepo.updateStatus(instance.id, 'RUNNING', updateFields);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Mark as ERROR if container creation fails
|
|
||||||
instance = await this.instanceRepo.updateStatus(instance.id, 'ERROR', {
|
instance = await this.instanceRepo.updateStatus(instance.id, 'ERROR', {
|
||||||
metadata: { error: err instanceof Error ? err.message : String(err) },
|
metadata: { error: err instanceof Error ? err.message : String(err) },
|
||||||
});
|
});
|
||||||
@@ -69,44 +181,16 @@ export class InstanceService {
|
|||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
async stop(id: string): Promise<McpInstance> {
|
/** Stop and remove a single instance. */
|
||||||
const instance = await this.getById(id);
|
private async removeOne(instance: McpInstance): Promise<void> {
|
||||||
if (!instance.containerId) {
|
|
||||||
return this.instanceRepo.updateStatus(id, 'STOPPED');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.instanceRepo.updateStatus(id, 'STOPPING');
|
|
||||||
|
|
||||||
try {
|
|
||||||
await this.orchestrator.stopContainer(instance.containerId);
|
|
||||||
return await this.instanceRepo.updateStatus(id, 'STOPPED');
|
|
||||||
} catch (err) {
|
|
||||||
return await this.instanceRepo.updateStatus(id, 'ERROR', {
|
|
||||||
metadata: { error: err instanceof Error ? err.message : String(err) },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async remove(id: string): Promise<void> {
|
|
||||||
const instance = await this.getById(id);
|
|
||||||
|
|
||||||
if (instance.containerId) {
|
if (instance.containerId) {
|
||||||
|
try {
|
||||||
|
await this.orchestrator.stopContainer(instance.containerId);
|
||||||
|
} catch { /* best-effort */ }
|
||||||
try {
|
try {
|
||||||
await this.orchestrator.removeContainer(instance.containerId, true);
|
await this.orchestrator.removeContainer(instance.containerId, true);
|
||||||
} catch {
|
} catch { /* best-effort */ }
|
||||||
// Container may already be gone, proceed with DB cleanup
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
await this.instanceRepo.delete(instance.id);
|
||||||
await this.instanceRepo.delete(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
async getLogs(id: string, opts?: { tail?: number }): Promise<{ stdout: string; stderr: string }> {
|
|
||||||
const instance = await this.getById(id);
|
|
||||||
if (!instance.containerId) {
|
|
||||||
return { stdout: '', stderr: '' };
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.orchestrator.getContainerLogs(instance.containerId, opts);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
12
src/mcpd/src/services/k8s/index.ts
Normal file
12
src/mcpd/src/services/k8s/index.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
export { KubernetesOrchestrator } from './kubernetes-orchestrator.js';
|
||||||
|
export { K8sClient, loadDefaultConfig, parseKubeconfig } from './k8s-client.js';
|
||||||
|
export type { K8sClientConfig, K8sResponse, K8sError } from './k8s-client.js';
|
||||||
|
export {
|
||||||
|
generatePodSpec,
|
||||||
|
generateDeploymentSpec,
|
||||||
|
generateNamespaceSpec,
|
||||||
|
formatMemory,
|
||||||
|
formatCpu,
|
||||||
|
sanitizeName,
|
||||||
|
} from './manifest-generator.js';
|
||||||
|
export type { K8sPodManifest, K8sDeploymentManifest, K8sNamespaceManifest } from './manifest-generator.js';
|
||||||
281
src/mcpd/src/services/k8s/k8s-client.ts
Normal file
281
src/mcpd/src/services/k8s/k8s-client.ts
Normal file
@@ -0,0 +1,281 @@
|
|||||||
|
import https from 'node:https';
|
||||||
|
import http from 'node:http';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
export interface K8sClientConfig {
|
||||||
|
apiServer: string;
|
||||||
|
token?: string;
|
||||||
|
caCert?: string;
|
||||||
|
namespace?: string;
|
||||||
|
/** Skip TLS verification (for dev clusters) */
|
||||||
|
insecure?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface K8sResponse<T = unknown> {
|
||||||
|
statusCode: number;
|
||||||
|
body: T;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface K8sError {
|
||||||
|
kind: 'Status';
|
||||||
|
apiVersion: 'v1';
|
||||||
|
status: 'Failure';
|
||||||
|
message: string;
|
||||||
|
reason: string;
|
||||||
|
code: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load config from in-cluster service account or KUBECONFIG env.
|
||||||
|
*/
|
||||||
|
export function loadDefaultConfig(): K8sClientConfig {
|
||||||
|
// In-cluster detection
|
||||||
|
const tokenPath = '/var/run/secrets/kubernetes.io/serviceaccount/token';
|
||||||
|
const caPath = '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt';
|
||||||
|
const nsPath = '/var/run/secrets/kubernetes.io/serviceaccount/namespace';
|
||||||
|
|
||||||
|
if (fs.existsSync(tokenPath)) {
|
||||||
|
const token = fs.readFileSync(tokenPath, 'utf-8').trim();
|
||||||
|
const namespace = fs.existsSync(nsPath) ? fs.readFileSync(nsPath, 'utf-8').trim() : 'default';
|
||||||
|
const config: K8sClientConfig = {
|
||||||
|
apiServer: `https://${process.env['KUBERNETES_SERVICE_HOST'] ?? 'kubernetes.default.svc'}:${process.env['KUBERNETES_SERVICE_PORT'] ?? '443'}`,
|
||||||
|
token,
|
||||||
|
namespace,
|
||||||
|
};
|
||||||
|
if (fs.existsSync(caPath)) {
|
||||||
|
config.caCert = fs.readFileSync(caPath, 'utf-8');
|
||||||
|
}
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: parse KUBECONFIG or ~/.kube/config
|
||||||
|
const kubeconfigPath = process.env['KUBECONFIG'] ?? path.join(process.env['HOME'] ?? '', '.kube', 'config');
|
||||||
|
if (fs.existsSync(kubeconfigPath)) {
|
||||||
|
return parseKubeconfig(fs.readFileSync(kubeconfigPath, 'utf-8'));
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('No Kubernetes configuration found (no in-cluster config or kubeconfig)');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Minimal kubeconfig parser - extracts current-context server and auth.
|
||||||
|
*/
|
||||||
|
export function parseKubeconfig(raw: string): K8sClientConfig {
|
||||||
|
// Simple YAML-like parser for kubeconfig (avoids yaml dependency)
|
||||||
|
const lines = raw.split('\n');
|
||||||
|
let currentContext = '';
|
||||||
|
let contextCluster = '';
|
||||||
|
let contextUser = '';
|
||||||
|
let serverUrl = '';
|
||||||
|
let token = '';
|
||||||
|
let caCert: string | undefined;
|
||||||
|
let namespace = 'default';
|
||||||
|
|
||||||
|
// Pass 1: find current-context
|
||||||
|
for (const line of lines) {
|
||||||
|
const match = line.match(/^current-context:\s*(.+)/);
|
||||||
|
if (match?.[1]) {
|
||||||
|
currentContext = match[1].trim();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pass 2: find context details
|
||||||
|
let inContexts = false;
|
||||||
|
let inTargetContext = false;
|
||||||
|
for (const line of lines) {
|
||||||
|
if (line.match(/^contexts:/)) { inContexts = true; continue; }
|
||||||
|
if (inContexts && line.match(/^\S/) && !line.match(/^contexts:/)) { inContexts = false; }
|
||||||
|
if (inContexts && line.includes(`name: ${currentContext}`)) { inTargetContext = true; continue; }
|
||||||
|
if (inTargetContext) {
|
||||||
|
const clusterMatch = line.match(/cluster:\s*(.+)/);
|
||||||
|
if (clusterMatch?.[1]) contextCluster = clusterMatch[1].trim();
|
||||||
|
const userMatch = line.match(/user:\s*(.+)/);
|
||||||
|
if (userMatch?.[1]) contextUser = userMatch[1].trim();
|
||||||
|
const nsMatch = line.match(/namespace:\s*(.+)/);
|
||||||
|
if (nsMatch?.[1]) namespace = nsMatch[1].trim();
|
||||||
|
if (contextCluster && contextUser) { inTargetContext = false; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pass 3: find cluster server
|
||||||
|
let inClusters = false;
|
||||||
|
let inTargetCluster = false;
|
||||||
|
for (const line of lines) {
|
||||||
|
if (line.match(/^clusters:/)) { inClusters = true; continue; }
|
||||||
|
if (inClusters && line.match(/^\S/) && !line.match(/^clusters:/)) { inClusters = false; }
|
||||||
|
if (inClusters && line.includes(`name: ${contextCluster}`)) { inTargetCluster = true; continue; }
|
||||||
|
if (inTargetCluster) {
|
||||||
|
const serverMatch = line.match(/server:\s*(.+)/);
|
||||||
|
if (serverMatch?.[1]) { serverUrl = serverMatch[1].trim(); inTargetCluster = false; }
|
||||||
|
const caMatch = line.match(/certificate-authority-data:\s*(.+)/);
|
||||||
|
if (caMatch?.[1]) caCert = Buffer.from(caMatch[1].trim(), 'base64').toString('utf-8');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pass 4: find user token
|
||||||
|
let inUsers = false;
|
||||||
|
let inTargetUser = false;
|
||||||
|
for (const line of lines) {
|
||||||
|
if (line.match(/^users:/)) { inUsers = true; continue; }
|
||||||
|
if (inUsers && line.match(/^\S/) && !line.match(/^users:/)) { inUsers = false; }
|
||||||
|
if (inUsers && line.includes(`name: ${contextUser}`)) { inTargetUser = true; continue; }
|
||||||
|
if (inTargetUser) {
|
||||||
|
const tokenMatch = line.match(/token:\s*(.+)/);
|
||||||
|
if (tokenMatch?.[1]) { token = tokenMatch[1].trim(); inTargetUser = false; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!serverUrl) {
|
||||||
|
throw new Error(`Could not parse kubeconfig: no server found for context "${currentContext}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const config: K8sClientConfig = {
|
||||||
|
apiServer: serverUrl,
|
||||||
|
namespace,
|
||||||
|
};
|
||||||
|
if (token) config.token = token;
|
||||||
|
if (caCert) config.caCert = caCert;
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class K8sClient {
|
||||||
|
private apiServer: string;
|
||||||
|
private token: string | undefined;
|
||||||
|
private caCert: string | undefined;
|
||||||
|
private insecure: boolean;
|
||||||
|
readonly defaultNamespace: string;
|
||||||
|
|
||||||
|
constructor(config: K8sClientConfig) {
|
||||||
|
this.apiServer = config.apiServer.replace(/\/$/, '');
|
||||||
|
this.token = config.token;
|
||||||
|
this.caCert = config.caCert;
|
||||||
|
this.insecure = config.insecure ?? false;
|
||||||
|
this.defaultNamespace = config.namespace ?? 'default';
|
||||||
|
}
|
||||||
|
|
||||||
|
async get<T = unknown>(path: string): Promise<K8sResponse<T>> {
|
||||||
|
return this.request<T>('GET', path);
|
||||||
|
}
|
||||||
|
|
||||||
|
async post<T = unknown>(path: string, body: unknown): Promise<K8sResponse<T>> {
|
||||||
|
return this.request<T>('POST', path, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete<T = unknown>(path: string): Promise<K8sResponse<T>> {
|
||||||
|
return this.request<T>('DELETE', path);
|
||||||
|
}
|
||||||
|
|
||||||
|
async patch<T = unknown>(path: string, body: unknown): Promise<K8sResponse<T>> {
|
||||||
|
return this.request<T>('PATCH', path, body, 'application/strategic-merge-patch+json');
|
||||||
|
}
|
||||||
|
|
||||||
|
private request<T>(method: string, urlPath: string, body?: unknown, contentType = 'application/json'): Promise<K8sResponse<T>> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const url = new URL(urlPath, this.apiServer);
|
||||||
|
const isHttps = url.protocol === 'https:';
|
||||||
|
const transport = isHttps ? https : http;
|
||||||
|
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
Accept: 'application/json',
|
||||||
|
};
|
||||||
|
if (this.token) {
|
||||||
|
headers['Authorization'] = `Bearer ${this.token}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
let payload: string | undefined;
|
||||||
|
if (body !== undefined) {
|
||||||
|
payload = JSON.stringify(body);
|
||||||
|
headers['Content-Type'] = contentType;
|
||||||
|
headers['Content-Length'] = String(Buffer.byteLength(payload));
|
||||||
|
}
|
||||||
|
|
||||||
|
const opts: https.RequestOptions = {
|
||||||
|
hostname: url.hostname,
|
||||||
|
port: url.port || (isHttps ? 443 : 80),
|
||||||
|
path: url.pathname + url.search,
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
timeout: 30000,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isHttps) {
|
||||||
|
if (this.caCert) {
|
||||||
|
opts.ca = this.caCert;
|
||||||
|
}
|
||||||
|
if (this.insecure) {
|
||||||
|
opts.rejectUnauthorized = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const req = transport.request(opts, (res) => {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
res.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||||
|
res.on('end', () => {
|
||||||
|
const raw = Buffer.concat(chunks).toString('utf-8');
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(raw) as T;
|
||||||
|
resolve({ statusCode: res.statusCode ?? 0, body: parsed });
|
||||||
|
} catch {
|
||||||
|
reject(new Error(`Invalid JSON from K8s API: ${raw.slice(0, 200)}`));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
req.on('error', reject);
|
||||||
|
req.on('timeout', () => {
|
||||||
|
req.destroy();
|
||||||
|
reject(new Error('K8s API request timed out'));
|
||||||
|
});
|
||||||
|
if (payload) req.write(payload);
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getLogs(namespace: string, podName: string, opts?: { tail?: number; since?: number }): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (opts?.tail !== undefined) params.set('tailLines', String(opts.tail));
|
||||||
|
if (opts?.since !== undefined) params.set('sinceSeconds', String(opts.since));
|
||||||
|
const qs = params.toString();
|
||||||
|
const urlPath = `/api/v1/namespaces/${namespace}/pods/${podName}/log${qs ? `?${qs}` : ''}`;
|
||||||
|
|
||||||
|
const url = new URL(urlPath, this.apiServer);
|
||||||
|
const isHttps = url.protocol === 'https:';
|
||||||
|
const transport = isHttps ? https : http;
|
||||||
|
|
||||||
|
const headers: Record<string, string> = {};
|
||||||
|
if (this.token) {
|
||||||
|
headers['Authorization'] = `Bearer ${this.token}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const reqOpts: https.RequestOptions = {
|
||||||
|
hostname: url.hostname,
|
||||||
|
port: url.port || (isHttps ? 443 : 80),
|
||||||
|
path: url.pathname + url.search,
|
||||||
|
method: 'GET',
|
||||||
|
headers,
|
||||||
|
timeout: 30000,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isHttps) {
|
||||||
|
if (this.caCert) reqOpts.ca = this.caCert;
|
||||||
|
if (this.insecure) reqOpts.rejectUnauthorized = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const req = transport.request(reqOpts, (res) => {
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
res.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||||
|
res.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
|
||||||
|
});
|
||||||
|
|
||||||
|
req.on('error', reject);
|
||||||
|
req.on('timeout', () => {
|
||||||
|
req.destroy();
|
||||||
|
reject(new Error('K8s log request timed out'));
|
||||||
|
});
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
200
src/mcpd/src/services/k8s/kubernetes-orchestrator.ts
Normal file
200
src/mcpd/src/services/k8s/kubernetes-orchestrator.ts
Normal file
@@ -0,0 +1,200 @@
|
|||||||
|
import type {
|
||||||
|
McpOrchestrator,
|
||||||
|
ContainerSpec,
|
||||||
|
ContainerInfo,
|
||||||
|
ContainerLogs,
|
||||||
|
} from '../orchestrator.js';
|
||||||
|
import { K8sClient } from './k8s-client.js';
|
||||||
|
import type { K8sClientConfig } from './k8s-client.js';
|
||||||
|
import { generatePodSpec, generateNamespaceSpec } from './manifest-generator.js';
|
||||||
|
|
||||||
|
interface K8sPodStatus {
|
||||||
|
metadata: {
|
||||||
|
name: string;
|
||||||
|
namespace: string;
|
||||||
|
creationTimestamp: string;
|
||||||
|
labels?: Record<string, string>;
|
||||||
|
};
|
||||||
|
status: {
|
||||||
|
phase: string;
|
||||||
|
containerStatuses?: Array<{
|
||||||
|
state: {
|
||||||
|
running?: Record<string, unknown>;
|
||||||
|
waiting?: { reason?: string };
|
||||||
|
terminated?: { reason?: string; exitCode?: number };
|
||||||
|
};
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
spec?: {
|
||||||
|
containers: Array<{
|
||||||
|
ports?: Array<{ containerPort: number }>;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface K8sPodList {
|
||||||
|
items: K8sPodStatus[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapPhase(phase: string, containerStatuses?: K8sPodStatus['status']['containerStatuses']): ContainerInfo['state'] {
|
||||||
|
// Check container-level status first for more granularity
|
||||||
|
if (containerStatuses && containerStatuses.length > 0) {
|
||||||
|
const cs = containerStatuses[0];
|
||||||
|
if (cs) {
|
||||||
|
if (cs.state.running) return 'running';
|
||||||
|
if (cs.state.waiting) return 'starting';
|
||||||
|
if (cs.state.terminated) return 'stopped';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (phase) {
|
||||||
|
case 'Running':
|
||||||
|
return 'running';
|
||||||
|
case 'Pending':
|
||||||
|
return 'starting';
|
||||||
|
case 'Succeeded':
|
||||||
|
case 'Failed':
|
||||||
|
return 'stopped';
|
||||||
|
default:
|
||||||
|
return 'unknown';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class KubernetesOrchestrator implements McpOrchestrator {
|
||||||
|
private client: K8sClient;
|
||||||
|
private namespace: string;
|
||||||
|
|
||||||
|
constructor(config: K8sClientConfig) {
|
||||||
|
this.client = new K8sClient(config);
|
||||||
|
this.namespace = config.namespace ?? 'default';
|
||||||
|
}
|
||||||
|
|
||||||
|
async ping(): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const res = await this.client.get('/api/v1');
|
||||||
|
return res.statusCode === 200;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async pullImage(_image: string): Promise<void> {
|
||||||
|
// K8s pulls images on pod scheduling - no pre-pull needed
|
||||||
|
}
|
||||||
|
|
||||||
|
async createContainer(spec: ContainerSpec): Promise<ContainerInfo> {
|
||||||
|
await this.ensureNamespace(this.namespace);
|
||||||
|
|
||||||
|
const manifest = generatePodSpec(spec, this.namespace);
|
||||||
|
const res = await this.client.post<K8sPodStatus>(
|
||||||
|
`/api/v1/namespaces/${this.namespace}/pods`,
|
||||||
|
manifest,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (res.statusCode >= 400) {
|
||||||
|
const err = res.body as unknown as { message?: string };
|
||||||
|
throw new Error(`Failed to create pod: ${err.message ?? `HTTP ${res.statusCode}`}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait briefly for pod to start scheduling
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||||
|
|
||||||
|
return this.inspectContainer(res.body.metadata.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
async stopContainer(containerId: string): Promise<void> {
|
||||||
|
// In K8s, "stopping" a pod means deleting it
|
||||||
|
await this.removeContainer(containerId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeContainer(containerId: string, _force?: boolean): Promise<void> {
|
||||||
|
const res = await this.client.delete(
|
||||||
|
`/api/v1/namespaces/${this.namespace}/pods/${containerId}`,
|
||||||
|
);
|
||||||
|
if (res.statusCode >= 400 && res.statusCode !== 404) {
|
||||||
|
const err = res.body as { message?: string };
|
||||||
|
throw new Error(`Failed to delete pod: ${err.message ?? `HTTP ${res.statusCode}`}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async inspectContainer(containerId: string): Promise<ContainerInfo> {
|
||||||
|
const res = await this.client.get<K8sPodStatus>(
|
||||||
|
`/api/v1/namespaces/${this.namespace}/pods/${containerId}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (res.statusCode === 404) {
|
||||||
|
throw new Error(`Pod "${containerId}" not found in namespace "${this.namespace}"`);
|
||||||
|
}
|
||||||
|
if (res.statusCode >= 400) {
|
||||||
|
const err = res.body as unknown as { message?: string };
|
||||||
|
throw new Error(`Failed to inspect pod: ${err.message ?? `HTTP ${res.statusCode}`}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const pod = res.body;
|
||||||
|
const result: ContainerInfo = {
|
||||||
|
containerId: pod.metadata.name,
|
||||||
|
name: pod.metadata.name,
|
||||||
|
state: mapPhase(pod.status.phase, pod.status.containerStatuses),
|
||||||
|
createdAt: new Date(pod.metadata.creationTimestamp),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Extract port from first container spec if available
|
||||||
|
const containers = pod.spec?.containers;
|
||||||
|
if (containers && containers.length > 0) {
|
||||||
|
const ports = containers[0]?.ports;
|
||||||
|
if (ports && ports.length > 0 && ports[0]) {
|
||||||
|
result.port = ports[0].containerPort;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getContainerLogs(
|
||||||
|
containerId: string,
|
||||||
|
opts?: { tail?: number; since?: number },
|
||||||
|
): Promise<ContainerLogs> {
|
||||||
|
const logOpts: { tail?: number; since?: number } = {
|
||||||
|
tail: opts?.tail ?? 100,
|
||||||
|
};
|
||||||
|
if (opts?.since !== undefined) {
|
||||||
|
logOpts.since = opts.since;
|
||||||
|
}
|
||||||
|
const stdout = await this.client.getLogs(this.namespace, containerId, logOpts);
|
||||||
|
return { stdout, stderr: '' };
|
||||||
|
}
|
||||||
|
|
||||||
|
async listContainers(namespace?: string): Promise<ContainerInfo[]> {
|
||||||
|
const ns = namespace ?? this.namespace;
|
||||||
|
const res = await this.client.get<K8sPodList>(
|
||||||
|
`/api/v1/namespaces/${ns}/pods?labelSelector=mcpctl.managed%3Dtrue`,
|
||||||
|
);
|
||||||
|
if (res.statusCode >= 400) return [];
|
||||||
|
|
||||||
|
return res.body.items.map((pod) => {
|
||||||
|
const info: ContainerInfo = {
|
||||||
|
containerId: pod.metadata.name,
|
||||||
|
name: pod.metadata.name,
|
||||||
|
state: mapPhase(pod.status.phase, pod.status.containerStatuses),
|
||||||
|
createdAt: new Date(pod.metadata.creationTimestamp),
|
||||||
|
};
|
||||||
|
return info;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async ensureNamespace(name: string): Promise<void> {
|
||||||
|
const res = await this.client.get(`/api/v1/namespaces/${name}`);
|
||||||
|
if (res.statusCode === 200) return;
|
||||||
|
|
||||||
|
const nsManifest = generateNamespaceSpec(name);
|
||||||
|
const createRes = await this.client.post('/api/v1/namespaces', nsManifest);
|
||||||
|
if (createRes.statusCode >= 400 && createRes.statusCode !== 409) {
|
||||||
|
const err = createRes.body as { message?: string };
|
||||||
|
throw new Error(`Failed to create namespace "${name}": ${err.message ?? `HTTP ${createRes.statusCode}`}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getNamespace(): string {
|
||||||
|
return this.namespace;
|
||||||
|
}
|
||||||
|
}
|
||||||
175
src/mcpd/src/services/k8s/manifest-generator.ts
Normal file
175
src/mcpd/src/services/k8s/manifest-generator.ts
Normal file
@@ -0,0 +1,175 @@
|
|||||||
|
import type { ContainerSpec } from '../orchestrator.js';
|
||||||
|
import { DEFAULT_MEMORY_LIMIT, DEFAULT_NANO_CPUS } from '../orchestrator.js';
|
||||||
|
|
||||||
|
const MCPCTL_LABEL = 'mcpctl.managed';
|
||||||
|
|
||||||
|
export interface K8sPodManifest {
|
||||||
|
apiVersion: 'v1';
|
||||||
|
kind: 'Pod';
|
||||||
|
metadata: {
|
||||||
|
name: string;
|
||||||
|
namespace: string;
|
||||||
|
labels: Record<string, string>;
|
||||||
|
};
|
||||||
|
spec: {
|
||||||
|
containers: Array<{
|
||||||
|
name: string;
|
||||||
|
image: string;
|
||||||
|
env?: Array<{ name: string; value: string }>;
|
||||||
|
ports?: Array<{ containerPort: number }>;
|
||||||
|
resources: {
|
||||||
|
limits: { memory: string; cpu: string };
|
||||||
|
requests: { memory: string; cpu: string };
|
||||||
|
};
|
||||||
|
securityContext: {
|
||||||
|
runAsNonRoot: boolean;
|
||||||
|
readOnlyRootFilesystem: boolean;
|
||||||
|
allowPrivilegeEscalation: boolean;
|
||||||
|
};
|
||||||
|
}>;
|
||||||
|
restartPolicy: 'Always' | 'Never' | 'OnFailure';
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface K8sDeploymentManifest {
|
||||||
|
apiVersion: 'apps/v1';
|
||||||
|
kind: 'Deployment';
|
||||||
|
metadata: {
|
||||||
|
name: string;
|
||||||
|
namespace: string;
|
||||||
|
labels: Record<string, string>;
|
||||||
|
};
|
||||||
|
spec: {
|
||||||
|
replicas: number;
|
||||||
|
selector: { matchLabels: Record<string, string> };
|
||||||
|
template: {
|
||||||
|
metadata: { labels: Record<string, string> };
|
||||||
|
spec: K8sPodManifest['spec'];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface K8sNamespaceManifest {
|
||||||
|
apiVersion: 'v1';
|
||||||
|
kind: 'Namespace';
|
||||||
|
metadata: { name: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatMemory(bytes: number): string {
|
||||||
|
if (bytes >= 1024 * 1024 * 1024) return `${Math.floor(bytes / (1024 * 1024 * 1024))}Gi`;
|
||||||
|
if (bytes >= 1024 * 1024) return `${Math.floor(bytes / (1024 * 1024))}Mi`;
|
||||||
|
if (bytes >= 1024) return `${Math.floor(bytes / 1024)}Ki`;
|
||||||
|
return `${bytes}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatCpu(nanoCpus: number): string {
|
||||||
|
const millicores = Math.floor(nanoCpus / 1_000_000);
|
||||||
|
return `${millicores}m`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeName(name: string): string {
|
||||||
|
return name.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/^-+|-+$/g, '').slice(0, 63);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildLabels(spec: ContainerSpec): Record<string, string> {
|
||||||
|
return {
|
||||||
|
[MCPCTL_LABEL]: 'true',
|
||||||
|
'app.kubernetes.io/managed-by': 'mcpctl',
|
||||||
|
'app.kubernetes.io/name': sanitizeName(spec.name),
|
||||||
|
...spec.labels,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildContainerSpec(spec: ContainerSpec) {
|
||||||
|
const memoryLimit = spec.memoryLimit ?? DEFAULT_MEMORY_LIMIT;
|
||||||
|
const nanoCpus = spec.nanoCpus ?? DEFAULT_NANO_CPUS;
|
||||||
|
const memStr = formatMemory(memoryLimit);
|
||||||
|
const cpuStr = formatCpu(nanoCpus);
|
||||||
|
|
||||||
|
const container: {
|
||||||
|
name: string;
|
||||||
|
image: string;
|
||||||
|
env?: Array<{ name: string; value: string }>;
|
||||||
|
ports?: Array<{ containerPort: number }>;
|
||||||
|
resources: { limits: { memory: string; cpu: string }; requests: { memory: string; cpu: string } };
|
||||||
|
securityContext: { runAsNonRoot: boolean; readOnlyRootFilesystem: boolean; allowPrivilegeEscalation: boolean };
|
||||||
|
} = {
|
||||||
|
name: sanitizeName(spec.name),
|
||||||
|
image: spec.image,
|
||||||
|
resources: {
|
||||||
|
limits: { memory: memStr, cpu: cpuStr },
|
||||||
|
requests: { memory: memStr, cpu: cpuStr },
|
||||||
|
},
|
||||||
|
securityContext: {
|
||||||
|
runAsNonRoot: true,
|
||||||
|
readOnlyRootFilesystem: true,
|
||||||
|
allowPrivilegeEscalation: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
if (spec.env && Object.keys(spec.env).length > 0) {
|
||||||
|
container.env = Object.entries(spec.env).map(([name, value]) => ({ name, value }));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (spec.containerPort) {
|
||||||
|
container.ports = [{ containerPort: spec.containerPort }];
|
||||||
|
}
|
||||||
|
|
||||||
|
return container;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generatePodSpec(spec: ContainerSpec, namespace: string): K8sPodManifest {
|
||||||
|
const labels = buildLabels(spec);
|
||||||
|
return {
|
||||||
|
apiVersion: 'v1',
|
||||||
|
kind: 'Pod',
|
||||||
|
metadata: {
|
||||||
|
name: sanitizeName(spec.name),
|
||||||
|
namespace,
|
||||||
|
labels,
|
||||||
|
},
|
||||||
|
spec: {
|
||||||
|
containers: [buildContainerSpec(spec)],
|
||||||
|
restartPolicy: 'Always',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generateDeploymentSpec(spec: ContainerSpec, namespace: string, replicas = 1): K8sDeploymentManifest {
|
||||||
|
const labels = buildLabels(spec);
|
||||||
|
const selectorLabels = {
|
||||||
|
'app.kubernetes.io/name': sanitizeName(spec.name),
|
||||||
|
[MCPCTL_LABEL]: 'true',
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
apiVersion: 'apps/v1',
|
||||||
|
kind: 'Deployment',
|
||||||
|
metadata: {
|
||||||
|
name: sanitizeName(spec.name),
|
||||||
|
namespace,
|
||||||
|
labels,
|
||||||
|
},
|
||||||
|
spec: {
|
||||||
|
replicas,
|
||||||
|
selector: { matchLabels: selectorLabels },
|
||||||
|
template: {
|
||||||
|
metadata: { labels },
|
||||||
|
spec: {
|
||||||
|
containers: [buildContainerSpec(spec)],
|
||||||
|
restartPolicy: 'Always',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generateNamespaceSpec(name: string): K8sNamespaceManifest {
|
||||||
|
return {
|
||||||
|
apiVersion: 'v1',
|
||||||
|
kind: 'Namespace',
|
||||||
|
metadata: { name },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export { sanitizeName, formatMemory, formatCpu };
|
||||||
214
src/mcpd/src/services/mcp-proxy-service.ts
Normal file
214
src/mcpd/src/services/mcp-proxy-service.ts
Normal file
@@ -0,0 +1,214 @@
|
|||||||
|
import type { McpInstance } from '@prisma/client';
|
||||||
|
import type { IMcpInstanceRepository, IMcpServerRepository } from '../repositories/interfaces.js';
|
||||||
|
import { NotFoundError } from './mcp-server.service.js';
|
||||||
|
import { InvalidStateError } from './instance.service.js';
|
||||||
|
|
||||||
|
export interface McpProxyRequest {
|
||||||
|
serverId: string;
|
||||||
|
method: string;
|
||||||
|
params?: Record<string, unknown> | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface McpProxyResponse {
|
||||||
|
jsonrpc: '2.0';
|
||||||
|
id: number;
|
||||||
|
result?: unknown;
|
||||||
|
error?: { code: number; message: string; data?: unknown };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a streamable-http SSE response body to extract the JSON-RPC payload.
|
||||||
|
* Streamable-http returns `event: message\ndata: {...}\n\n` format.
|
||||||
|
*/
|
||||||
|
function parseStreamableResponse(body: string): McpProxyResponse {
|
||||||
|
for (const line of body.split('\n')) {
|
||||||
|
const trimmed = line.trim();
|
||||||
|
if (trimmed.startsWith('data: ')) {
|
||||||
|
return JSON.parse(trimmed.slice(6)) as McpProxyResponse;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// If body is plain JSON (no SSE framing), parse directly
|
||||||
|
return JSON.parse(body) as McpProxyResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class McpProxyService {
|
||||||
|
/** Session IDs per server for streamable-http protocol */
|
||||||
|
private sessions = new Map<string, string>();
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly instanceRepo: IMcpInstanceRepository,
|
||||||
|
private readonly serverRepo: IMcpServerRepository,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async execute(request: McpProxyRequest): Promise<McpProxyResponse> {
|
||||||
|
const server = await this.serverRepo.findById(request.serverId);
|
||||||
|
|
||||||
|
// External server: proxy directly to externalUrl
|
||||||
|
if (server?.externalUrl) {
|
||||||
|
return this.sendToExternal(server.id, server.externalUrl, request.method, request.params);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Managed server: find running instance
|
||||||
|
const instances = await this.instanceRepo.findAll(request.serverId);
|
||||||
|
const running = instances.find((i) => i.status === 'RUNNING');
|
||||||
|
|
||||||
|
if (!running) {
|
||||||
|
throw new NotFoundError(`No running instance found for server '${request.serverId}'`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (running.port === null || running.port === undefined) {
|
||||||
|
throw new InvalidStateError(
|
||||||
|
`Running instance '${running.id}' for server '${request.serverId}' has no port assigned`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.sendJsonRpc(running, request.method, request.params);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a JSON-RPC request to an external MCP server.
|
||||||
|
* Handles streamable-http protocol (session management + SSE response parsing).
|
||||||
|
*/
|
||||||
|
private async sendToExternal(
|
||||||
|
serverId: string,
|
||||||
|
url: string,
|
||||||
|
method: string,
|
||||||
|
params?: Record<string, unknown>,
|
||||||
|
): Promise<McpProxyResponse> {
|
||||||
|
// Ensure we have a session (initialize on first call)
|
||||||
|
if (!this.sessions.has(serverId)) {
|
||||||
|
await this.initSession(serverId, url);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sessionId = this.sessions.get(serverId);
|
||||||
|
|
||||||
|
const body: Record<string, unknown> = {
|
||||||
|
jsonrpc: '2.0',
|
||||||
|
id: 1,
|
||||||
|
method,
|
||||||
|
};
|
||||||
|
if (params !== undefined) {
|
||||||
|
body.params = params;
|
||||||
|
}
|
||||||
|
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Accept': 'application/json, text/event-stream',
|
||||||
|
};
|
||||||
|
if (sessionId) {
|
||||||
|
headers['Mcp-Session-Id'] = sessionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers,
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
// Session expired? Clear and retry once
|
||||||
|
if (response.status === 400 || response.status === 404) {
|
||||||
|
this.sessions.delete(serverId);
|
||||||
|
return this.sendToExternal(serverId, url, method, params);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
jsonrpc: '2.0',
|
||||||
|
id: 1,
|
||||||
|
error: {
|
||||||
|
code: -32000,
|
||||||
|
message: `External MCP server returned HTTP ${response.status}: ${response.statusText}`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = await response.text();
|
||||||
|
return parseStreamableResponse(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize a streamable-http session with an external server.
|
||||||
|
* Sends `initialize` and `notifications/initialized`, caches the session ID.
|
||||||
|
*/
|
||||||
|
private async initSession(serverId: string, url: string): Promise<void> {
|
||||||
|
const initBody = {
|
||||||
|
jsonrpc: '2.0',
|
||||||
|
id: 1,
|
||||||
|
method: 'initialize',
|
||||||
|
params: {
|
||||||
|
protocolVersion: '2025-03-26',
|
||||||
|
capabilities: {},
|
||||||
|
clientInfo: { name: 'mcpctl', version: '0.1.0' },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Accept': 'application/json, text/event-stream',
|
||||||
|
},
|
||||||
|
body: JSON.stringify(initBody),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Failed to initialize session: HTTP ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sessionId = response.headers.get('mcp-session-id');
|
||||||
|
if (sessionId) {
|
||||||
|
this.sessions.set(serverId, sessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send notifications/initialized
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Accept': 'application/json, text/event-stream',
|
||||||
|
};
|
||||||
|
if (sessionId) {
|
||||||
|
headers['Mcp-Session-Id'] = sessionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers,
|
||||||
|
body: JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async sendJsonRpc(
|
||||||
|
instance: McpInstance,
|
||||||
|
method: string,
|
||||||
|
params?: Record<string, unknown>,
|
||||||
|
): Promise<McpProxyResponse> {
|
||||||
|
const url = `http://localhost:${instance.port}`;
|
||||||
|
|
||||||
|
const body: Record<string, unknown> = {
|
||||||
|
jsonrpc: '2.0',
|
||||||
|
id: 1,
|
||||||
|
method,
|
||||||
|
};
|
||||||
|
if (params !== undefined) {
|
||||||
|
body.params = params;
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return {
|
||||||
|
jsonrpc: '2.0',
|
||||||
|
id: 1,
|
||||||
|
error: {
|
||||||
|
code: -32000,
|
||||||
|
message: `MCP server returned HTTP ${response.status}: ${response.statusText}`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = (await response.json()) as McpProxyResponse;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,18 @@
|
|||||||
import type { McpServer } from '@prisma/client';
|
import type { McpServer } from '@prisma/client';
|
||||||
import type { IMcpServerRepository } from '../repositories/interfaces.js';
|
import type { IMcpServerRepository } from '../repositories/interfaces.js';
|
||||||
|
import type { InstanceService } from './instance.service.js';
|
||||||
import { CreateMcpServerSchema, UpdateMcpServerSchema } from '../validation/mcp-server.schema.js';
|
import { CreateMcpServerSchema, UpdateMcpServerSchema } from '../validation/mcp-server.schema.js';
|
||||||
|
|
||||||
export class McpServerService {
|
export class McpServerService {
|
||||||
|
private instanceService: InstanceService | null = null;
|
||||||
|
|
||||||
constructor(private readonly repo: IMcpServerRepository) {}
|
constructor(private readonly repo: IMcpServerRepository) {}
|
||||||
|
|
||||||
|
/** Set after construction to avoid circular dependency. */
|
||||||
|
setInstanceService(instanceService: InstanceService): void {
|
||||||
|
this.instanceService = instanceService;
|
||||||
|
}
|
||||||
|
|
||||||
async list(): Promise<McpServer[]> {
|
async list(): Promise<McpServer[]> {
|
||||||
return this.repo.findAll();
|
return this.repo.findAll();
|
||||||
}
|
}
|
||||||
@@ -48,6 +56,10 @@ export class McpServerService {
|
|||||||
async delete(id: string): Promise<void> {
|
async delete(id: string): Promise<void> {
|
||||||
// Verify exists
|
// Verify exists
|
||||||
await this.getById(id);
|
await this.getById(id);
|
||||||
|
// Stop all containers before DB cascade
|
||||||
|
if (this.instanceService) {
|
||||||
|
await this.instanceService.removeAllForServer(id);
|
||||||
|
}
|
||||||
await this.repo.delete(id);
|
await this.repo.delete(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
103
src/mcpd/src/services/metrics-collector.ts
Normal file
103
src/mcpd/src/services/metrics-collector.ts
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
export interface InstanceMetrics {
|
||||||
|
instanceId: string;
|
||||||
|
status: 'healthy' | 'unhealthy' | 'unknown';
|
||||||
|
uptime: number;
|
||||||
|
requestCount: number;
|
||||||
|
errorCount: number;
|
||||||
|
lastRequestAt: Date | null;
|
||||||
|
latencyMs: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class MetricsCollector {
|
||||||
|
private metrics = new Map<string, InstanceMetrics>();
|
||||||
|
private startTimes = new Map<string, Date>();
|
||||||
|
|
||||||
|
register(instanceId: string): void {
|
||||||
|
if (!this.metrics.has(instanceId)) {
|
||||||
|
this.metrics.set(instanceId, {
|
||||||
|
instanceId,
|
||||||
|
status: 'unknown',
|
||||||
|
uptime: 0,
|
||||||
|
requestCount: 0,
|
||||||
|
errorCount: 0,
|
||||||
|
lastRequestAt: null,
|
||||||
|
latencyMs: [],
|
||||||
|
});
|
||||||
|
this.startTimes.set(instanceId, new Date());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unregister(instanceId: string): void {
|
||||||
|
this.metrics.delete(instanceId);
|
||||||
|
this.startTimes.delete(instanceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
recordRequest(instanceId: string, latencyMs?: number): void {
|
||||||
|
const m = this.ensureMetrics(instanceId);
|
||||||
|
m.requestCount++;
|
||||||
|
m.lastRequestAt = new Date();
|
||||||
|
if (latencyMs !== undefined) {
|
||||||
|
m.latencyMs.push(latencyMs);
|
||||||
|
// Keep only last 1000 latency samples
|
||||||
|
if (m.latencyMs.length > 1000) {
|
||||||
|
m.latencyMs = m.latencyMs.slice(-1000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
recordError(instanceId: string): void {
|
||||||
|
const m = this.ensureMetrics(instanceId);
|
||||||
|
m.errorCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
updateStatus(instanceId: string, status: InstanceMetrics['status']): void {
|
||||||
|
const m = this.ensureMetrics(instanceId);
|
||||||
|
m.status = status;
|
||||||
|
}
|
||||||
|
|
||||||
|
getMetrics(instanceId: string): InstanceMetrics | undefined {
|
||||||
|
const m = this.metrics.get(instanceId);
|
||||||
|
if (!m) return undefined;
|
||||||
|
|
||||||
|
// Compute uptime from start time
|
||||||
|
const start = this.startTimes.get(instanceId);
|
||||||
|
if (start) {
|
||||||
|
m.uptime = (Date.now() - start.getTime()) / 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ...m, latencyMs: [...m.latencyMs] };
|
||||||
|
}
|
||||||
|
|
||||||
|
getAllMetrics(): InstanceMetrics[] {
|
||||||
|
return [...this.metrics.keys()]
|
||||||
|
.map((id) => this.getMetrics(id))
|
||||||
|
.filter((m): m is InstanceMetrics => m !== undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
getErrorRate(instanceId: string): number {
|
||||||
|
const m = this.metrics.get(instanceId);
|
||||||
|
if (!m || m.requestCount === 0) return 0;
|
||||||
|
return m.errorCount / m.requestCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
getAverageLatency(instanceId: string): number {
|
||||||
|
const m = this.metrics.get(instanceId);
|
||||||
|
if (!m || m.latencyMs.length === 0) return 0;
|
||||||
|
const sum = m.latencyMs.reduce((a, b) => a + b, 0);
|
||||||
|
return sum / m.latencyMs.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
reset(): void {
|
||||||
|
this.metrics.clear();
|
||||||
|
this.startTimes.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensureMetrics(instanceId: string): InstanceMetrics {
|
||||||
|
let m = this.metrics.get(instanceId);
|
||||||
|
if (!m) {
|
||||||
|
this.register(instanceId);
|
||||||
|
m = this.metrics.get(instanceId)!;
|
||||||
|
}
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,8 @@ export interface ContainerSpec {
|
|||||||
image: string;
|
image: string;
|
||||||
/** Human-readable name (used as container name prefix) */
|
/** Human-readable name (used as container name prefix) */
|
||||||
name: string;
|
name: string;
|
||||||
|
/** Custom command to run (overrides image CMD) */
|
||||||
|
command?: string[];
|
||||||
/** Environment variables */
|
/** Environment variables */
|
||||||
env?: Record<string, string>;
|
env?: Record<string, string>;
|
||||||
/** Host port to bind (null = auto-assign) */
|
/** Host port to bind (null = auto-assign) */
|
||||||
|
|||||||
@@ -14,6 +14,10 @@ export const CreateMcpServerSchema = z.object({
|
|||||||
dockerImage: z.string().max(200).optional(),
|
dockerImage: z.string().max(200).optional(),
|
||||||
transport: z.enum(['STDIO', 'SSE', 'STREAMABLE_HTTP']).default('STDIO'),
|
transport: z.enum(['STDIO', 'SSE', 'STREAMABLE_HTTP']).default('STDIO'),
|
||||||
repositoryUrl: z.string().url().optional(),
|
repositoryUrl: z.string().url().optional(),
|
||||||
|
externalUrl: z.string().url().optional(),
|
||||||
|
command: z.array(z.string()).optional(),
|
||||||
|
containerPort: z.number().int().min(1).max(65535).optional(),
|
||||||
|
replicas: z.number().int().min(0).max(10).default(1),
|
||||||
envTemplate: z.array(EnvTemplateEntrySchema).default([]),
|
envTemplate: z.array(EnvTemplateEntrySchema).default([]),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -23,6 +27,10 @@ export const UpdateMcpServerSchema = z.object({
|
|||||||
dockerImage: z.string().max(200).nullable().optional(),
|
dockerImage: z.string().max(200).nullable().optional(),
|
||||||
transport: z.enum(['STDIO', 'SSE', 'STREAMABLE_HTTP']).optional(),
|
transport: z.enum(['STDIO', 'SSE', 'STREAMABLE_HTTP']).optional(),
|
||||||
repositoryUrl: z.string().url().nullable().optional(),
|
repositoryUrl: z.string().url().nullable().optional(),
|
||||||
|
externalUrl: z.string().url().nullable().optional(),
|
||||||
|
command: z.array(z.string()).nullable().optional(),
|
||||||
|
containerPort: z.number().int().min(1).max(65535).nullable().optional(),
|
||||||
|
replicas: z.number().int().min(0).max(10).optional(),
|
||||||
envTemplate: z.array(EnvTemplateEntrySchema).optional(),
|
envTemplate: z.array(EnvTemplateEntrySchema).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
111
src/mcpd/tests/audit-log-routes.test.ts
Normal file
111
src/mcpd/tests/audit-log-routes.test.ts
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||||
|
import Fastify from 'fastify';
|
||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import { registerAuditLogRoutes } from '../src/routes/audit-logs.js';
|
||||||
|
import { AuditLogService } from '../src/services/audit-log.service.js';
|
||||||
|
import type { IAuditLogRepository } from '../src/repositories/interfaces.js';
|
||||||
|
import { errorHandler } from '../src/middleware/error-handler.js';
|
||||||
|
|
||||||
|
function makeLog(id: string) {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
userId: 'user-1',
|
||||||
|
action: 'CREATE',
|
||||||
|
resource: 'servers',
|
||||||
|
resourceId: null,
|
||||||
|
details: {},
|
||||||
|
createdAt: new Date('2025-01-15T00:00:00Z'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function mockRepo(): IAuditLogRepository {
|
||||||
|
return {
|
||||||
|
findAll: vi.fn(async () => [makeLog('log-1'), makeLog('log-2')]),
|
||||||
|
findById: vi.fn(async () => null),
|
||||||
|
create: vi.fn(async () => makeLog('new-log')),
|
||||||
|
count: vi.fn(async () => 2),
|
||||||
|
deleteOlderThan: vi.fn(async () => 3),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Audit Log Routes', () => {
|
||||||
|
let app: FastifyInstance;
|
||||||
|
let repo: ReturnType<typeof mockRepo>;
|
||||||
|
let service: AuditLogService;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
app = Fastify();
|
||||||
|
app.setErrorHandler(errorHandler);
|
||||||
|
repo = mockRepo();
|
||||||
|
service = new AuditLogService(repo, 90);
|
||||||
|
registerAuditLogRoutes(app, service);
|
||||||
|
await app.ready();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/audit-logs', () => {
|
||||||
|
it('returns paginated audit logs', async () => {
|
||||||
|
const res = await app.inject({ method: 'GET', url: '/api/v1/audit-logs' });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const body = res.json();
|
||||||
|
expect(body.logs).toHaveLength(2);
|
||||||
|
expect(body.total).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes query filters to service', async () => {
|
||||||
|
await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/audit-logs?userId=user-1&action=CREATE&resource=servers&limit=10&offset=5',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(repo.findAll).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
userId: 'user-1',
|
||||||
|
action: 'CREATE',
|
||||||
|
resource: 'servers',
|
||||||
|
limit: 10,
|
||||||
|
offset: 5,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes date range filters', async () => {
|
||||||
|
await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/audit-logs?since=2025-01-01T00:00:00Z&until=2025-12-31T23:59:59Z',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(repo.findAll).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
since: expect.any(Date),
|
||||||
|
until: expect.any(Date),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/audit-logs/:id', () => {
|
||||||
|
it('returns a specific log entry', async () => {
|
||||||
|
vi.mocked(repo.findById).mockResolvedValue(makeLog('log-1'));
|
||||||
|
const res = await app.inject({ method: 'GET', url: '/api/v1/audit-logs/log-1' });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
expect(res.json().id).toBe('log-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns 404 for missing log', async () => {
|
||||||
|
const res = await app.inject({ method: 'GET', url: '/api/v1/audit-logs/nonexistent' });
|
||||||
|
expect(res.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('POST /api/v1/audit-logs/purge', () => {
|
||||||
|
it('purges expired logs and returns count', async () => {
|
||||||
|
const res = await app.inject({ method: 'POST', url: '/api/v1/audit-logs/purge' });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
expect(res.json().deleted).toBe(3);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
151
src/mcpd/tests/audit-log-service.test.ts
Normal file
151
src/mcpd/tests/audit-log-service.test.ts
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import { AuditLogService } from '../src/services/audit-log.service.js';
|
||||||
|
import type { IAuditLogRepository } from '../src/repositories/interfaces.js';
|
||||||
|
import { NotFoundError } from '../src/services/mcp-server.service.js';
|
||||||
|
|
||||||
|
function makeLog(overrides: Partial<{ id: string; userId: string; action: string; resource: string; resourceId: string | null; createdAt: Date }> = {}) {
|
||||||
|
return {
|
||||||
|
id: overrides.id ?? 'log-1',
|
||||||
|
userId: overrides.userId ?? 'user-1',
|
||||||
|
action: overrides.action ?? 'CREATE',
|
||||||
|
resource: overrides.resource ?? 'servers',
|
||||||
|
resourceId: overrides.resourceId ?? null,
|
||||||
|
details: {},
|
||||||
|
createdAt: overrides.createdAt ?? new Date('2025-01-15T00:00:00Z'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function mockRepo(): IAuditLogRepository {
|
||||||
|
return {
|
||||||
|
findAll: vi.fn(async () => [makeLog()]),
|
||||||
|
findById: vi.fn(async () => null),
|
||||||
|
create: vi.fn(async (data) => ({
|
||||||
|
id: 'new-log',
|
||||||
|
userId: data.userId,
|
||||||
|
action: data.action,
|
||||||
|
resource: data.resource,
|
||||||
|
resourceId: data.resourceId ?? null,
|
||||||
|
details: data.details ?? {},
|
||||||
|
createdAt: new Date(),
|
||||||
|
})),
|
||||||
|
count: vi.fn(async () => 1),
|
||||||
|
deleteOlderThan: vi.fn(async () => 5),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('AuditLogService', () => {
|
||||||
|
let repo: ReturnType<typeof mockRepo>;
|
||||||
|
let service: AuditLogService;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
repo = mockRepo();
|
||||||
|
service = new AuditLogService(repo, 90);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('list', () => {
|
||||||
|
it('returns logs with total count', async () => {
|
||||||
|
const result = await service.list();
|
||||||
|
expect(result.logs).toHaveLength(1);
|
||||||
|
expect(result.total).toBe(1);
|
||||||
|
expect(repo.findAll).toHaveBeenCalled();
|
||||||
|
expect(repo.count).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes filter params to repository', async () => {
|
||||||
|
await service.list({
|
||||||
|
userId: 'user-1',
|
||||||
|
action: 'CREATE',
|
||||||
|
resource: 'servers',
|
||||||
|
limit: 50,
|
||||||
|
offset: 10,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(repo.findAll).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
userId: 'user-1',
|
||||||
|
action: 'CREATE',
|
||||||
|
resource: 'servers',
|
||||||
|
limit: 50,
|
||||||
|
offset: 10,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses date strings in since/until', async () => {
|
||||||
|
await service.list({
|
||||||
|
since: '2025-01-01T00:00:00Z',
|
||||||
|
until: '2025-12-31T23:59:59Z',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(repo.findAll).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
since: expect.any(Date),
|
||||||
|
until: expect.any(Date),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getById', () => {
|
||||||
|
it('returns a log entry', async () => {
|
||||||
|
vi.mocked(repo.findById).mockResolvedValue(makeLog({ id: 'log-1' }));
|
||||||
|
const log = await service.getById('log-1');
|
||||||
|
expect(log.id).toBe('log-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws NotFoundError when log does not exist', async () => {
|
||||||
|
await expect(service.getById('nonexistent')).rejects.toThrow(NotFoundError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('create', () => {
|
||||||
|
it('creates an audit log entry', async () => {
|
||||||
|
const log = await service.create({
|
||||||
|
userId: 'user-1',
|
||||||
|
action: 'CREATE',
|
||||||
|
resource: 'servers',
|
||||||
|
details: { method: 'POST' },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(log.id).toBe('new-log');
|
||||||
|
expect(repo.create).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
userId: 'user-1',
|
||||||
|
action: 'CREATE',
|
||||||
|
resource: 'servers',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates log with optional resourceId', async () => {
|
||||||
|
await service.create({
|
||||||
|
userId: 'user-1',
|
||||||
|
action: 'DELETE',
|
||||||
|
resource: 'servers',
|
||||||
|
resourceId: 'srv-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(repo.create).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ resourceId: 'srv-1' }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('purgeExpired', () => {
|
||||||
|
it('deletes logs older than retention period', async () => {
|
||||||
|
const deleted = await service.purgeExpired();
|
||||||
|
expect(deleted).toBe(5);
|
||||||
|
expect(repo.deleteOlderThan).toHaveBeenCalledWith(expect.any(Date));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses configured retention days', async () => {
|
||||||
|
const customService = new AuditLogService(repo, 30);
|
||||||
|
await customService.purgeExpired();
|
||||||
|
|
||||||
|
const cutoff = vi.mocked(repo.deleteOlderThan).mock.calls[0]?.[0] as Date;
|
||||||
|
const now = new Date();
|
||||||
|
const daysDiff = Math.round((now.getTime() - cutoff.getTime()) / (1000 * 60 * 60 * 24));
|
||||||
|
expect(daysDiff).toBe(30);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
336
src/mcpd/tests/backup.test.ts
Normal file
336
src/mcpd/tests/backup.test.ts
Normal file
@@ -0,0 +1,336 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import Fastify from 'fastify';
|
||||||
|
import { BackupService } from '../src/services/backup/backup-service.js';
|
||||||
|
import { RestoreService } from '../src/services/backup/restore-service.js';
|
||||||
|
import { encrypt, decrypt, isSensitiveKey } from '../src/services/backup/crypto.js';
|
||||||
|
import { registerBackupRoutes } from '../src/routes/backup.js';
|
||||||
|
import type { IMcpServerRepository, IMcpProfileRepository } from '../src/repositories/interfaces.js';
|
||||||
|
import type { IProjectRepository } from '../src/repositories/project.repository.js';
|
||||||
|
|
||||||
|
// Mock data
|
||||||
|
const mockServers = [
|
||||||
|
{
|
||||||
|
id: 's1', name: 'github', description: 'GitHub MCP', packageName: '@mcp/github',
|
||||||
|
dockerImage: null, transport: 'STDIO' as const, repositoryUrl: null,
|
||||||
|
envTemplate: [], version: 1, createdAt: new Date(), updatedAt: new Date(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 's2', name: 'slack', description: 'Slack MCP', packageName: null,
|
||||||
|
dockerImage: 'mcp/slack:latest', transport: 'SSE' as const, repositoryUrl: null,
|
||||||
|
envTemplate: [], version: 1, createdAt: new Date(), updatedAt: new Date(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const mockProfiles = [
|
||||||
|
{
|
||||||
|
id: 'p1', name: 'default', serverId: 's1', permissions: ['read'],
|
||||||
|
envOverrides: { GITHUB_TOKEN: 'ghp_secret123' },
|
||||||
|
version: 1, createdAt: new Date(), updatedAt: new Date(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const mockProjects = [
|
||||||
|
{
|
||||||
|
id: 'proj1', name: 'my-project', description: 'Test project',
|
||||||
|
ownerId: 'user1', version: 1, createdAt: new Date(), updatedAt: new Date(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
function mockServerRepo(): IMcpServerRepository {
|
||||||
|
return {
|
||||||
|
findAll: vi.fn(async () => [...mockServers]),
|
||||||
|
findById: vi.fn(async (id: string) => mockServers.find((s) => s.id === id) ?? null),
|
||||||
|
findByName: vi.fn(async (name: string) => mockServers.find((s) => s.name === name) ?? null),
|
||||||
|
create: vi.fn(async (data) => ({ id: 'new-s', ...data, envTemplate: [], version: 1, createdAt: new Date(), updatedAt: new Date() } as typeof mockServers[0])),
|
||||||
|
update: vi.fn(async (id, data) => ({ ...mockServers.find((s) => s.id === id)!, ...data })),
|
||||||
|
delete: vi.fn(async () => {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function mockProfileRepo(): IMcpProfileRepository {
|
||||||
|
return {
|
||||||
|
findAll: vi.fn(async () => [...mockProfiles]),
|
||||||
|
findById: vi.fn(async (id: string) => mockProfiles.find((p) => p.id === id) ?? null),
|
||||||
|
findByServerAndName: vi.fn(async () => null),
|
||||||
|
create: vi.fn(async (data) => ({ id: 'new-p', ...data, version: 1, createdAt: new Date(), updatedAt: new Date() } as typeof mockProfiles[0])),
|
||||||
|
update: vi.fn(async (id, data) => ({ ...mockProfiles.find((p) => p.id === id)!, ...data })),
|
||||||
|
delete: vi.fn(async () => {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function mockProjectRepo(): IProjectRepository {
|
||||||
|
return {
|
||||||
|
findAll: vi.fn(async () => [...mockProjects]),
|
||||||
|
findById: vi.fn(async (id: string) => mockProjects.find((p) => p.id === id) ?? null),
|
||||||
|
findByName: vi.fn(async () => null),
|
||||||
|
create: vi.fn(async (data) => ({ id: 'new-proj', ...data, version: 1, createdAt: new Date(), updatedAt: new Date() } as typeof mockProjects[0])),
|
||||||
|
update: vi.fn(async (id, data) => ({ ...mockProjects.find((p) => p.id === id)!, ...data })),
|
||||||
|
delete: vi.fn(async () => {}),
|
||||||
|
setProfiles: vi.fn(async () => {}),
|
||||||
|
getProfileIds: vi.fn(async () => ['p1']),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Crypto', () => {
|
||||||
|
it('encrypts and decrypts successfully', () => {
|
||||||
|
const data = 'hello secret world';
|
||||||
|
const password = 'my-password-123';
|
||||||
|
const encrypted = encrypt(data, password);
|
||||||
|
|
||||||
|
expect(encrypted.algorithm).toBe('aes-256-gcm');
|
||||||
|
expect(encrypted.ciphertext).not.toBe(data);
|
||||||
|
|
||||||
|
const decrypted = decrypt(encrypted, password);
|
||||||
|
expect(decrypted).toBe(data);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails with wrong password', () => {
|
||||||
|
const encrypted = encrypt('secret', 'correct-password');
|
||||||
|
expect(() => decrypt(encrypted, 'wrong-password')).toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles large data', () => {
|
||||||
|
const data = 'x'.repeat(10000);
|
||||||
|
const encrypted = encrypt(data, 'pass');
|
||||||
|
expect(decrypt(encrypted, 'pass')).toBe(data);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('detects sensitive keys', () => {
|
||||||
|
expect(isSensitiveKey('GITHUB_TOKEN')).toBe(true);
|
||||||
|
expect(isSensitiveKey('API_KEY')).toBe(true);
|
||||||
|
expect(isSensitiveKey('DATABASE_PASSWORD')).toBe(true);
|
||||||
|
expect(isSensitiveKey('AWS_SECRET')).toBe(true);
|
||||||
|
expect(isSensitiveKey('MY_SECRET_KEY')).toBe(true);
|
||||||
|
expect(isSensitiveKey('CREDENTIALS')).toBe(true);
|
||||||
|
expect(isSensitiveKey('PORT')).toBe(false);
|
||||||
|
expect(isSensitiveKey('DATABASE_URL')).toBe(false);
|
||||||
|
expect(isSensitiveKey('NODE_ENV')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('BackupService', () => {
|
||||||
|
let backupService: BackupService;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
backupService = new BackupService(mockServerRepo(), mockProfileRepo(), mockProjectRepo());
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates backup with all resources', async () => {
|
||||||
|
const bundle = await backupService.createBackup();
|
||||||
|
|
||||||
|
expect(bundle.version).toBe('1');
|
||||||
|
expect(bundle.encrypted).toBe(false);
|
||||||
|
expect(bundle.servers).toHaveLength(2);
|
||||||
|
expect(bundle.profiles).toHaveLength(1);
|
||||||
|
expect(bundle.projects).toHaveLength(1);
|
||||||
|
expect(bundle.servers[0]!.name).toBe('github');
|
||||||
|
expect(bundle.profiles[0]!.serverName).toBe('github');
|
||||||
|
expect(bundle.projects[0]!.name).toBe('my-project');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters resources', async () => {
|
||||||
|
const bundle = await backupService.createBackup({ resources: ['servers'] });
|
||||||
|
expect(bundle.servers).toHaveLength(2);
|
||||||
|
expect(bundle.profiles).toHaveLength(0);
|
||||||
|
expect(bundle.projects).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('encrypts sensitive env values when password provided', async () => {
|
||||||
|
const bundle = await backupService.createBackup({ password: 'test-pass' });
|
||||||
|
|
||||||
|
expect(bundle.encrypted).toBe(true);
|
||||||
|
expect(bundle.encryptedSecrets).toBeDefined();
|
||||||
|
// The GITHUB_TOKEN should be replaced with placeholder
|
||||||
|
const overrides = bundle.profiles[0]!.envOverrides as Record<string, string>;
|
||||||
|
expect(overrides['GITHUB_TOKEN']).toContain('__ENCRYPTED:');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles empty repositories', async () => {
|
||||||
|
const emptyServerRepo = mockServerRepo();
|
||||||
|
(emptyServerRepo.findAll as ReturnType<typeof vi.fn>).mockResolvedValue([]);
|
||||||
|
const emptyProfileRepo = mockProfileRepo();
|
||||||
|
(emptyProfileRepo.findAll as ReturnType<typeof vi.fn>).mockResolvedValue([]);
|
||||||
|
const emptyProjectRepo = mockProjectRepo();
|
||||||
|
(emptyProjectRepo.findAll as ReturnType<typeof vi.fn>).mockResolvedValue([]);
|
||||||
|
|
||||||
|
const service = new BackupService(emptyServerRepo, emptyProfileRepo, emptyProjectRepo);
|
||||||
|
const bundle = await service.createBackup();
|
||||||
|
|
||||||
|
expect(bundle.servers).toHaveLength(0);
|
||||||
|
expect(bundle.profiles).toHaveLength(0);
|
||||||
|
expect(bundle.projects).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('RestoreService', () => {
|
||||||
|
let restoreService: RestoreService;
|
||||||
|
let serverRepo: IMcpServerRepository;
|
||||||
|
let profileRepo: IMcpProfileRepository;
|
||||||
|
let projectRepo: IProjectRepository;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
serverRepo = mockServerRepo();
|
||||||
|
profileRepo = mockProfileRepo();
|
||||||
|
projectRepo = mockProjectRepo();
|
||||||
|
// Default: nothing exists yet
|
||||||
|
(serverRepo.findByName as ReturnType<typeof vi.fn>).mockResolvedValue(null);
|
||||||
|
(profileRepo.findByServerAndName as ReturnType<typeof vi.fn>).mockResolvedValue(null);
|
||||||
|
(projectRepo.findByName as ReturnType<typeof vi.fn>).mockResolvedValue(null);
|
||||||
|
restoreService = new RestoreService(serverRepo, profileRepo, projectRepo);
|
||||||
|
});
|
||||||
|
|
||||||
|
const validBundle = {
|
||||||
|
version: '1',
|
||||||
|
mcpctlVersion: '0.1.0',
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
encrypted: false,
|
||||||
|
servers: [{ name: 'github', description: 'GitHub', packageName: null, dockerImage: null, transport: 'STDIO', repositoryUrl: null, envTemplate: [] }],
|
||||||
|
profiles: [{ name: 'default', serverName: 'github', permissions: ['read'], envOverrides: {} }],
|
||||||
|
projects: [{ name: 'test-proj', description: 'Test', profileNames: ['default'] }],
|
||||||
|
};
|
||||||
|
|
||||||
|
it('validates valid bundle', () => {
|
||||||
|
expect(restoreService.validateBundle(validBundle)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects invalid bundle', () => {
|
||||||
|
expect(restoreService.validateBundle(null)).toBe(false);
|
||||||
|
expect(restoreService.validateBundle({})).toBe(false);
|
||||||
|
expect(restoreService.validateBundle({ version: '1' })).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('restores all resources', async () => {
|
||||||
|
const result = await restoreService.restore(validBundle);
|
||||||
|
|
||||||
|
expect(result.serversCreated).toBe(1);
|
||||||
|
expect(result.profilesCreated).toBe(1);
|
||||||
|
expect(result.projectsCreated).toBe(1);
|
||||||
|
expect(result.errors).toHaveLength(0);
|
||||||
|
expect(serverRepo.create).toHaveBeenCalled();
|
||||||
|
expect(profileRepo.create).toHaveBeenCalled();
|
||||||
|
expect(projectRepo.create).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips existing resources with skip strategy', async () => {
|
||||||
|
(serverRepo.findByName as ReturnType<typeof vi.fn>).mockResolvedValue(mockServers[0]);
|
||||||
|
const result = await restoreService.restore(validBundle, { conflictStrategy: 'skip' });
|
||||||
|
|
||||||
|
expect(result.serversSkipped).toBe(1);
|
||||||
|
expect(result.serversCreated).toBe(0);
|
||||||
|
expect(serverRepo.create).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('aborts on conflict with fail strategy', async () => {
|
||||||
|
(serverRepo.findByName as ReturnType<typeof vi.fn>).mockResolvedValue(mockServers[0]);
|
||||||
|
const result = await restoreService.restore(validBundle, { conflictStrategy: 'fail' });
|
||||||
|
|
||||||
|
expect(result.errors).toContain('Server "github" already exists');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('overwrites existing with overwrite strategy', async () => {
|
||||||
|
(serverRepo.findByName as ReturnType<typeof vi.fn>).mockResolvedValue(mockServers[0]);
|
||||||
|
const result = await restoreService.restore(validBundle, { conflictStrategy: 'overwrite' });
|
||||||
|
|
||||||
|
expect(result.serversCreated).toBe(1);
|
||||||
|
expect(serverRepo.update).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails restore with encrypted bundle and no password', async () => {
|
||||||
|
const encBundle = { ...validBundle, encrypted: true, encryptedSecrets: encrypt('{}', 'pw') };
|
||||||
|
const result = await restoreService.restore(encBundle);
|
||||||
|
expect(result.errors).toContain('Backup is encrypted but no password provided');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('restores encrypted bundle with correct password', async () => {
|
||||||
|
const secrets = { 'profile:default:API_KEY': 'secret-val' };
|
||||||
|
const encBundle = {
|
||||||
|
...validBundle,
|
||||||
|
encrypted: true,
|
||||||
|
encryptedSecrets: encrypt(JSON.stringify(secrets), 'test-pw'),
|
||||||
|
profiles: [{ ...validBundle.profiles[0]!, envOverrides: { API_KEY: '__ENCRYPTED:profile:default:API_KEY__' } }],
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await restoreService.restore(encBundle, { password: 'test-pw' });
|
||||||
|
expect(result.errors).toHaveLength(0);
|
||||||
|
expect(result.profilesCreated).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails with wrong decryption password', async () => {
|
||||||
|
const encBundle = {
|
||||||
|
...validBundle,
|
||||||
|
encrypted: true,
|
||||||
|
encryptedSecrets: encrypt('{"key":"val"}', 'correct'),
|
||||||
|
};
|
||||||
|
const result = await restoreService.restore(encBundle, { password: 'wrong' });
|
||||||
|
expect(result.errors[0]).toContain('Failed to decrypt');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Backup Routes', () => {
|
||||||
|
let backupService: BackupService;
|
||||||
|
let restoreService: RestoreService;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
const sRepo = mockServerRepo();
|
||||||
|
const pRepo = mockProfileRepo();
|
||||||
|
const prRepo = mockProjectRepo();
|
||||||
|
backupService = new BackupService(sRepo, pRepo, prRepo);
|
||||||
|
|
||||||
|
const rSRepo = mockServerRepo();
|
||||||
|
(rSRepo.findByName as ReturnType<typeof vi.fn>).mockResolvedValue(null);
|
||||||
|
const rPRepo = mockProfileRepo();
|
||||||
|
(rPRepo.findByServerAndName as ReturnType<typeof vi.fn>).mockResolvedValue(null);
|
||||||
|
const rPrRepo = mockProjectRepo();
|
||||||
|
(rPrRepo.findByName as ReturnType<typeof vi.fn>).mockResolvedValue(null);
|
||||||
|
restoreService = new RestoreService(rSRepo, rPRepo, rPrRepo);
|
||||||
|
});
|
||||||
|
|
||||||
|
async function buildApp() {
|
||||||
|
const app = Fastify();
|
||||||
|
registerBackupRoutes(app, { backupService, restoreService });
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
it('POST /api/v1/backup returns bundle', async () => {
|
||||||
|
const app = await buildApp();
|
||||||
|
const res = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/backup',
|
||||||
|
payload: {},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const body = res.json();
|
||||||
|
expect(body.version).toBe('1');
|
||||||
|
expect(body.servers).toBeDefined();
|
||||||
|
expect(body.profiles).toBeDefined();
|
||||||
|
expect(body.projects).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('POST /api/v1/restore imports bundle', async () => {
|
||||||
|
const app = await buildApp();
|
||||||
|
const bundle = await backupService.createBackup();
|
||||||
|
|
||||||
|
const res = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/restore',
|
||||||
|
payload: { bundle, conflictStrategy: 'skip' },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const body = res.json();
|
||||||
|
expect(body.serversCreated).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('POST /api/v1/restore rejects invalid bundle', async () => {
|
||||||
|
const app = await buildApp();
|
||||||
|
const res = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/restore',
|
||||||
|
payload: { bundle: { invalid: true } },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(res.statusCode).toBe(400);
|
||||||
|
expect(res.json().error).toContain('Invalid');
|
||||||
|
});
|
||||||
|
});
|
||||||
304
src/mcpd/tests/health-monitoring.test.ts
Normal file
304
src/mcpd/tests/health-monitoring.test.ts
Normal file
@@ -0,0 +1,304 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import Fastify from 'fastify';
|
||||||
|
import { MetricsCollector } from '../src/services/metrics-collector.js';
|
||||||
|
import { HealthAggregator } from '../src/services/health-aggregator.js';
|
||||||
|
import type { McpOrchestrator } from '../src/services/orchestrator.js';
|
||||||
|
import { registerHealthMonitoringRoutes } from '../src/routes/health-monitoring.js';
|
||||||
|
|
||||||
|
function mockOrchestrator(available = true): McpOrchestrator {
|
||||||
|
return {
|
||||||
|
ping: vi.fn(async () => available),
|
||||||
|
pullImage: vi.fn(async () => {}),
|
||||||
|
createContainer: vi.fn(async () => ({
|
||||||
|
containerId: 'c1', name: 'test', state: 'running' as const, createdAt: new Date(),
|
||||||
|
})),
|
||||||
|
stopContainer: vi.fn(async () => {}),
|
||||||
|
removeContainer: vi.fn(async () => {}),
|
||||||
|
inspectContainer: vi.fn(async () => ({
|
||||||
|
containerId: 'c1', name: 'test', state: 'running' as const, createdAt: new Date(),
|
||||||
|
})),
|
||||||
|
getContainerLogs: vi.fn(async () => ({ stdout: '', stderr: '' })),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('MetricsCollector', () => {
|
||||||
|
let collector: MetricsCollector;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
collector = new MetricsCollector();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('registers and retrieves instance metrics', () => {
|
||||||
|
collector.register('inst-1');
|
||||||
|
const m = collector.getMetrics('inst-1');
|
||||||
|
expect(m).toBeDefined();
|
||||||
|
expect(m!.instanceId).toBe('inst-1');
|
||||||
|
expect(m!.requestCount).toBe(0);
|
||||||
|
expect(m!.errorCount).toBe(0);
|
||||||
|
expect(m!.status).toBe('unknown');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns undefined for unregistered instance', () => {
|
||||||
|
expect(collector.getMetrics('nonexistent')).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('records requests and increments count', () => {
|
||||||
|
collector.register('inst-1');
|
||||||
|
collector.recordRequest('inst-1', 50);
|
||||||
|
collector.recordRequest('inst-1', 100);
|
||||||
|
const m = collector.getMetrics('inst-1')!;
|
||||||
|
expect(m.requestCount).toBe(2);
|
||||||
|
expect(m.lastRequestAt).not.toBeNull();
|
||||||
|
expect(m.latencyMs).toEqual([50, 100]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('records errors', () => {
|
||||||
|
collector.register('inst-1');
|
||||||
|
collector.recordError('inst-1');
|
||||||
|
collector.recordError('inst-1');
|
||||||
|
expect(collector.getMetrics('inst-1')!.errorCount).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('auto-registers on recordRequest for unknown instance', () => {
|
||||||
|
collector.recordRequest('new-inst');
|
||||||
|
expect(collector.getMetrics('new-inst')).toBeDefined();
|
||||||
|
expect(collector.getMetrics('new-inst')!.requestCount).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('calculates error rate', () => {
|
||||||
|
collector.register('inst-1');
|
||||||
|
collector.recordRequest('inst-1');
|
||||||
|
collector.recordRequest('inst-1');
|
||||||
|
collector.recordError('inst-1');
|
||||||
|
expect(collector.getErrorRate('inst-1')).toBe(0.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns 0 error rate when no requests', () => {
|
||||||
|
collector.register('inst-1');
|
||||||
|
expect(collector.getErrorRate('inst-1')).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('calculates average latency', () => {
|
||||||
|
collector.register('inst-1');
|
||||||
|
collector.recordRequest('inst-1', 100);
|
||||||
|
collector.recordRequest('inst-1', 200);
|
||||||
|
collector.recordRequest('inst-1', 300);
|
||||||
|
expect(collector.getAverageLatency('inst-1')).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns 0 average latency when no samples', () => {
|
||||||
|
collector.register('inst-1');
|
||||||
|
expect(collector.getAverageLatency('inst-1')).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('updates status', () => {
|
||||||
|
collector.register('inst-1');
|
||||||
|
collector.updateStatus('inst-1', 'healthy');
|
||||||
|
expect(collector.getMetrics('inst-1')!.status).toBe('healthy');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getAllMetrics returns all registered instances', () => {
|
||||||
|
collector.register('a');
|
||||||
|
collector.register('b');
|
||||||
|
collector.register('c');
|
||||||
|
const all = collector.getAllMetrics();
|
||||||
|
expect(all).toHaveLength(3);
|
||||||
|
expect(all.map((m) => m.instanceId).sort()).toEqual(['a', 'b', 'c']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('unregister removes instance', () => {
|
||||||
|
collector.register('inst-1');
|
||||||
|
collector.unregister('inst-1');
|
||||||
|
expect(collector.getMetrics('inst-1')).toBeUndefined();
|
||||||
|
expect(collector.getAllMetrics()).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reset clears all metrics', () => {
|
||||||
|
collector.register('a');
|
||||||
|
collector.register('b');
|
||||||
|
collector.reset();
|
||||||
|
expect(collector.getAllMetrics()).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('computes uptime from registration time', () => {
|
||||||
|
collector.register('inst-1');
|
||||||
|
const m = collector.getMetrics('inst-1')!;
|
||||||
|
expect(m.uptime).toBeGreaterThanOrEqual(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('HealthAggregator', () => {
|
||||||
|
let collector: MetricsCollector;
|
||||||
|
let orchestrator: McpOrchestrator;
|
||||||
|
let aggregator: HealthAggregator;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
collector = new MetricsCollector();
|
||||||
|
orchestrator = mockOrchestrator(true);
|
||||||
|
aggregator = new HealthAggregator(collector, orchestrator);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports healthy when all instances healthy', async () => {
|
||||||
|
collector.register('a');
|
||||||
|
collector.register('b');
|
||||||
|
collector.updateStatus('a', 'healthy');
|
||||||
|
collector.updateStatus('b', 'healthy');
|
||||||
|
|
||||||
|
const overview = await aggregator.getOverview();
|
||||||
|
expect(overview.overallStatus).toBe('healthy');
|
||||||
|
expect(overview.totalInstances).toBe(2);
|
||||||
|
expect(overview.healthyCount).toBe(2);
|
||||||
|
expect(overview.unhealthyCount).toBe(0);
|
||||||
|
expect(overview.runtimeAvailable).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports degraded when some instances unhealthy', async () => {
|
||||||
|
collector.register('a');
|
||||||
|
collector.register('b');
|
||||||
|
collector.updateStatus('a', 'healthy');
|
||||||
|
collector.updateStatus('b', 'unhealthy');
|
||||||
|
|
||||||
|
const overview = await aggregator.getOverview();
|
||||||
|
expect(overview.overallStatus).toBe('degraded');
|
||||||
|
expect(overview.unhealthyCount).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports degraded when some instances unknown', async () => {
|
||||||
|
collector.register('a');
|
||||||
|
collector.updateStatus('a', 'healthy');
|
||||||
|
collector.register('b'); // status remains 'unknown'
|
||||||
|
|
||||||
|
const overview = await aggregator.getOverview();
|
||||||
|
expect(overview.overallStatus).toBe('degraded');
|
||||||
|
expect(overview.unknownCount).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports unhealthy when all instances unhealthy', async () => {
|
||||||
|
collector.register('a');
|
||||||
|
collector.updateStatus('a', 'unhealthy');
|
||||||
|
|
||||||
|
const overview = await aggregator.getOverview();
|
||||||
|
expect(overview.overallStatus).toBe('unhealthy');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports unhealthy when runtime unavailable', async () => {
|
||||||
|
orchestrator = mockOrchestrator(false);
|
||||||
|
aggregator = new HealthAggregator(collector, orchestrator);
|
||||||
|
|
||||||
|
const overview = await aggregator.getOverview();
|
||||||
|
expect(overview.overallStatus).toBe('unhealthy');
|
||||||
|
expect(overview.runtimeAvailable).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports healthy with no instances and runtime available', async () => {
|
||||||
|
const overview = await aggregator.getOverview();
|
||||||
|
expect(overview.overallStatus).toBe('healthy');
|
||||||
|
expect(overview.totalInstances).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('computes aggregate error rate', async () => {
|
||||||
|
collector.register('a');
|
||||||
|
collector.recordRequest('a');
|
||||||
|
collector.recordRequest('a');
|
||||||
|
collector.recordError('a');
|
||||||
|
|
||||||
|
const overview = await aggregator.getOverview();
|
||||||
|
expect(overview.aggregateErrorRate).toBe(0.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getInstanceHealth returns instance details', () => {
|
||||||
|
collector.register('inst-1');
|
||||||
|
collector.updateStatus('inst-1', 'healthy');
|
||||||
|
collector.recordRequest('inst-1', 150);
|
||||||
|
collector.recordError('inst-1');
|
||||||
|
|
||||||
|
const health = aggregator.getInstanceHealth('inst-1');
|
||||||
|
expect(health).toBeDefined();
|
||||||
|
expect(health!.instanceId).toBe('inst-1');
|
||||||
|
expect(health!.status).toBe('healthy');
|
||||||
|
expect(health!.requestCount).toBe(1);
|
||||||
|
expect(health!.errorCount).toBe(1);
|
||||||
|
expect(health!.errorRate).toBe(1);
|
||||||
|
expect(health!.averageLatencyMs).toBe(150);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getInstanceHealth returns undefined for unknown instance', () => {
|
||||||
|
expect(aggregator.getInstanceHealth('nonexistent')).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Health Monitoring Routes', () => {
|
||||||
|
let collector: MetricsCollector;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
collector = new MetricsCollector();
|
||||||
|
});
|
||||||
|
|
||||||
|
async function buildApp(runtimeAvailable = true) {
|
||||||
|
const orchestrator = mockOrchestrator(runtimeAvailable);
|
||||||
|
const aggregator = new HealthAggregator(collector, orchestrator);
|
||||||
|
const app = Fastify();
|
||||||
|
registerHealthMonitoringRoutes(app, {
|
||||||
|
healthAggregator: aggregator,
|
||||||
|
metricsCollector: collector,
|
||||||
|
});
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
it('GET /api/v1/health/overview returns system health', async () => {
|
||||||
|
collector.register('a');
|
||||||
|
collector.updateStatus('a', 'healthy');
|
||||||
|
const app = await buildApp();
|
||||||
|
|
||||||
|
const res = await app.inject({ method: 'GET', url: '/api/v1/health/overview' });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const body = res.json();
|
||||||
|
expect(body.overallStatus).toBe('healthy');
|
||||||
|
expect(body.totalInstances).toBe(1);
|
||||||
|
expect(body.runtimeAvailable).toBe(true);
|
||||||
|
expect(body.timestamp).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('GET /api/v1/health/instances/:id returns instance health', async () => {
|
||||||
|
collector.register('inst-1');
|
||||||
|
collector.updateStatus('inst-1', 'healthy');
|
||||||
|
collector.recordRequest('inst-1', 42);
|
||||||
|
const app = await buildApp();
|
||||||
|
|
||||||
|
const res = await app.inject({ method: 'GET', url: '/api/v1/health/instances/inst-1' });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const body = res.json();
|
||||||
|
expect(body.instanceId).toBe('inst-1');
|
||||||
|
expect(body.status).toBe('healthy');
|
||||||
|
expect(body.requestCount).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('GET /api/v1/health/instances/:id returns 404 for unknown', async () => {
|
||||||
|
const app = await buildApp();
|
||||||
|
|
||||||
|
const res = await app.inject({ method: 'GET', url: '/api/v1/health/instances/nonexistent' });
|
||||||
|
expect(res.statusCode).toBe(404);
|
||||||
|
expect(res.json().error).toContain('not found');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('GET /api/v1/metrics returns all instance metrics', async () => {
|
||||||
|
collector.register('a');
|
||||||
|
collector.register('b');
|
||||||
|
collector.recordRequest('a');
|
||||||
|
const app = await buildApp();
|
||||||
|
|
||||||
|
const res = await app.inject({ method: 'GET', url: '/api/v1/metrics' });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const body = res.json();
|
||||||
|
expect(body.instances).toHaveLength(2);
|
||||||
|
expect(body.timestamp).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('GET /api/v1/metrics returns empty with no instances', async () => {
|
||||||
|
const app = await buildApp();
|
||||||
|
|
||||||
|
const res = await app.inject({ method: 'GET', url: '/api/v1/metrics' });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
expect(res.json().instances).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
import { InstanceService } from '../src/services/instance.service.js';
|
import { InstanceService, InvalidStateError } from '../src/services/instance.service.js';
|
||||||
import { NotFoundError } from '../src/services/mcp-server.service.js';
|
import { NotFoundError } from '../src/services/mcp-server.service.js';
|
||||||
import type { IMcpInstanceRepository, IMcpServerRepository } from '../src/repositories/interfaces.js';
|
import type { IMcpInstanceRepository, IMcpServerRepository } from '../src/repositories/interfaces.js';
|
||||||
import type { McpOrchestrator } from '../src/services/orchestrator.js';
|
import type { McpOrchestrator } from '../src/services/orchestrator.js';
|
||||||
|
import type { McpInstance } from '@prisma/client';
|
||||||
|
|
||||||
function mockInstanceRepo(): IMcpInstanceRepository {
|
function mockInstanceRepo(): IMcpInstanceRepository {
|
||||||
return {
|
return {
|
||||||
@@ -69,6 +70,41 @@ function mockOrchestrator(): McpOrchestrator {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function makeServer(overrides: Partial<{ id: string; name: string; replicas: number; dockerImage: string | null; externalUrl: string | null; transport: string; command: unknown; containerPort: number | null }> = {}) {
|
||||||
|
return {
|
||||||
|
id: overrides.id ?? 'srv-1',
|
||||||
|
name: overrides.name ?? 'slack',
|
||||||
|
dockerImage: overrides.dockerImage ?? 'ghcr.io/slack-mcp:latest',
|
||||||
|
packageName: null,
|
||||||
|
transport: overrides.transport ?? 'STDIO',
|
||||||
|
description: '',
|
||||||
|
repositoryUrl: null,
|
||||||
|
externalUrl: overrides.externalUrl ?? null,
|
||||||
|
command: overrides.command ?? null,
|
||||||
|
containerPort: overrides.containerPort ?? null,
|
||||||
|
replicas: overrides.replicas ?? 1,
|
||||||
|
envTemplate: [],
|
||||||
|
version: 1,
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeInstance(overrides: Partial<McpInstance> = {}): McpInstance {
|
||||||
|
return {
|
||||||
|
id: 'inst-1',
|
||||||
|
serverId: 'srv-1',
|
||||||
|
containerId: overrides.containerId ?? 'ctr-abc',
|
||||||
|
status: overrides.status ?? 'RUNNING',
|
||||||
|
port: overrides.port ?? 3000,
|
||||||
|
metadata: overrides.metadata ?? {},
|
||||||
|
version: 1,
|
||||||
|
createdAt: overrides.createdAt ?? new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
...overrides,
|
||||||
|
} as McpInstance;
|
||||||
|
}
|
||||||
|
|
||||||
describe('InstanceService', () => {
|
describe('InstanceService', () => {
|
||||||
let instanceRepo: ReturnType<typeof mockInstanceRepo>;
|
let instanceRepo: ReturnType<typeof mockInstanceRepo>;
|
||||||
let serverRepo: ReturnType<typeof mockServerRepo>;
|
let serverRepo: ReturnType<typeof mockServerRepo>;
|
||||||
@@ -101,122 +137,98 @@ describe('InstanceService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('returns instance when found', async () => {
|
it('returns instance when found', async () => {
|
||||||
vi.mocked(instanceRepo.findById).mockResolvedValue({ id: 'inst-1' } as never);
|
vi.mocked(instanceRepo.findById).mockResolvedValue(makeInstance({ id: 'inst-1' }));
|
||||||
const result = await service.getById('inst-1');
|
const result = await service.getById('inst-1');
|
||||||
expect(result.id).toBe('inst-1');
|
expect(result.id).toBe('inst-1');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('start', () => {
|
describe('reconcile', () => {
|
||||||
|
it('starts instances when below desired replicas', async () => {
|
||||||
|
vi.mocked(serverRepo.findById).mockResolvedValue(makeServer({ replicas: 2 }));
|
||||||
|
vi.mocked(instanceRepo.findAll).mockResolvedValue([]);
|
||||||
|
|
||||||
|
await service.reconcile('srv-1');
|
||||||
|
|
||||||
|
// Should create 2 instances
|
||||||
|
expect(instanceRepo.create).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does nothing when at desired replicas', async () => {
|
||||||
|
vi.mocked(serverRepo.findById).mockResolvedValue(makeServer({ replicas: 1 }));
|
||||||
|
vi.mocked(instanceRepo.findAll).mockResolvedValue([makeInstance({ status: 'RUNNING' })]);
|
||||||
|
|
||||||
|
await service.reconcile('srv-1');
|
||||||
|
|
||||||
|
expect(instanceRepo.create).not.toHaveBeenCalled();
|
||||||
|
expect(instanceRepo.delete).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('removes excess instances when above desired replicas', async () => {
|
||||||
|
vi.mocked(serverRepo.findById).mockResolvedValue(makeServer({ replicas: 1 }));
|
||||||
|
vi.mocked(instanceRepo.findAll).mockResolvedValue([
|
||||||
|
makeInstance({ id: 'inst-old', createdAt: new Date('2025-01-01') }),
|
||||||
|
makeInstance({ id: 'inst-new', createdAt: new Date('2025-06-01') }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
await service.reconcile('srv-1');
|
||||||
|
|
||||||
|
// Should remove the oldest one
|
||||||
|
expect(orchestrator.stopContainer).toHaveBeenCalledTimes(1);
|
||||||
|
expect(instanceRepo.delete).toHaveBeenCalledWith('inst-old');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates external instances without Docker', async () => {
|
||||||
|
vi.mocked(serverRepo.findById).mockResolvedValue(
|
||||||
|
makeServer({ replicas: 1, externalUrl: 'http://localhost:8086/mcp', dockerImage: null }),
|
||||||
|
);
|
||||||
|
vi.mocked(instanceRepo.findAll).mockResolvedValue([]);
|
||||||
|
|
||||||
|
await service.reconcile('srv-1');
|
||||||
|
|
||||||
|
expect(instanceRepo.create).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ status: 'RUNNING', metadata: expect.objectContaining({ external: true }) }),
|
||||||
|
);
|
||||||
|
expect(orchestrator.createContainer).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles replicas: 0 by removing all instances', async () => {
|
||||||
|
vi.mocked(serverRepo.findById).mockResolvedValue(makeServer({ replicas: 0 }));
|
||||||
|
vi.mocked(instanceRepo.findAll).mockResolvedValue([makeInstance()]);
|
||||||
|
|
||||||
|
await service.reconcile('srv-1');
|
||||||
|
|
||||||
|
expect(instanceRepo.delete).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
it('throws NotFoundError for unknown server', async () => {
|
it('throws NotFoundError for unknown server', async () => {
|
||||||
await expect(service.start('missing')).rejects.toThrow(NotFoundError);
|
await expect(service.reconcile('missing')).rejects.toThrow(NotFoundError);
|
||||||
});
|
|
||||||
|
|
||||||
it('creates instance and starts container', async () => {
|
|
||||||
vi.mocked(serverRepo.findById).mockResolvedValue({
|
|
||||||
id: 'srv-1', name: 'slack', dockerImage: 'ghcr.io/slack-mcp:latest',
|
|
||||||
packageName: null, transport: 'STDIO', description: '', repositoryUrl: null,
|
|
||||||
envTemplate: [], version: 1, createdAt: new Date(), updatedAt: new Date(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await service.start('srv-1');
|
|
||||||
|
|
||||||
expect(instanceRepo.create).toHaveBeenCalledWith({
|
|
||||||
serverId: 'srv-1',
|
|
||||||
status: 'STARTING',
|
|
||||||
});
|
|
||||||
expect(orchestrator.createContainer).toHaveBeenCalled();
|
|
||||||
expect(instanceRepo.updateStatus).toHaveBeenCalledWith(
|
|
||||||
'inst-1', 'RUNNING',
|
|
||||||
expect.objectContaining({ containerId: 'ctr-abc123' }),
|
|
||||||
);
|
|
||||||
expect(result.status).toBe('RUNNING');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('marks instance as ERROR on container failure', async () => {
|
|
||||||
vi.mocked(serverRepo.findById).mockResolvedValue({
|
|
||||||
id: 'srv-1', name: 'slack', dockerImage: 'ghcr.io/slack-mcp:latest',
|
|
||||||
packageName: null, transport: 'STDIO', description: '', repositoryUrl: null,
|
|
||||||
envTemplate: [], version: 1, createdAt: new Date(), updatedAt: new Date(),
|
|
||||||
});
|
|
||||||
vi.mocked(orchestrator.createContainer).mockRejectedValue(new Error('Docker unavailable'));
|
|
||||||
|
|
||||||
const result = await service.start('srv-1');
|
|
||||||
|
|
||||||
expect(instanceRepo.updateStatus).toHaveBeenCalledWith(
|
|
||||||
'inst-1', 'ERROR',
|
|
||||||
expect.objectContaining({ metadata: { error: 'Docker unavailable' } }),
|
|
||||||
);
|
|
||||||
expect(result.status).toBe('ERROR');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('uses dockerImage for container spec', async () => {
|
|
||||||
vi.mocked(serverRepo.findById).mockResolvedValue({
|
|
||||||
id: 'srv-1', name: 'slack', dockerImage: 'myregistry.com/slack:v1',
|
|
||||||
packageName: '@slack/mcp', transport: 'SSE', description: '', repositoryUrl: null,
|
|
||||||
envTemplate: [], version: 1, createdAt: new Date(), updatedAt: new Date(),
|
|
||||||
});
|
|
||||||
|
|
||||||
await service.start('srv-1');
|
|
||||||
|
|
||||||
const spec = vi.mocked(orchestrator.createContainer).mock.calls[0]?.[0];
|
|
||||||
expect(spec?.image).toBe('myregistry.com/slack:v1');
|
|
||||||
expect(spec?.containerPort).toBe(3000); // SSE transport
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('stop', () => {
|
|
||||||
it('throws NotFoundError for missing instance', async () => {
|
|
||||||
await expect(service.stop('missing')).rejects.toThrow(NotFoundError);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('stops a running container', async () => {
|
|
||||||
vi.mocked(instanceRepo.findById).mockResolvedValue({
|
|
||||||
id: 'inst-1', containerId: 'ctr-abc', status: 'RUNNING',
|
|
||||||
serverId: 'srv-1', port: 3000, metadata: {},
|
|
||||||
version: 1, createdAt: new Date(), updatedAt: new Date(),
|
|
||||||
});
|
|
||||||
|
|
||||||
await service.stop('inst-1');
|
|
||||||
|
|
||||||
expect(orchestrator.stopContainer).toHaveBeenCalledWith('ctr-abc');
|
|
||||||
expect(instanceRepo.updateStatus).toHaveBeenCalledWith('inst-1', 'STOPPED');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('handles stop without containerId', async () => {
|
|
||||||
vi.mocked(instanceRepo.findById).mockResolvedValue({
|
|
||||||
id: 'inst-1', containerId: null, status: 'ERROR',
|
|
||||||
serverId: 'srv-1', port: null, metadata: {},
|
|
||||||
version: 1, createdAt: new Date(), updatedAt: new Date(),
|
|
||||||
});
|
|
||||||
|
|
||||||
await service.stop('inst-1');
|
|
||||||
|
|
||||||
expect(orchestrator.stopContainer).not.toHaveBeenCalled();
|
|
||||||
expect(instanceRepo.updateStatus).toHaveBeenCalledWith('inst-1', 'STOPPED');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('remove', () => {
|
describe('remove', () => {
|
||||||
it('removes container and DB record', async () => {
|
it('stops container and deletes DB record', async () => {
|
||||||
vi.mocked(instanceRepo.findById).mockResolvedValue({
|
vi.mocked(instanceRepo.findById).mockResolvedValue(makeInstance({ containerId: 'ctr-abc' }));
|
||||||
id: 'inst-1', containerId: 'ctr-abc', status: 'STOPPED',
|
|
||||||
serverId: 'srv-1', port: null, metadata: {},
|
const result = await service.remove('inst-1');
|
||||||
version: 1, createdAt: new Date(), updatedAt: new Date(),
|
|
||||||
});
|
expect(orchestrator.stopContainer).toHaveBeenCalledWith('ctr-abc');
|
||||||
|
expect(orchestrator.removeContainer).toHaveBeenCalledWith('ctr-abc', true);
|
||||||
|
expect(instanceRepo.delete).toHaveBeenCalledWith('inst-1');
|
||||||
|
expect(result.serverId).toBe('srv-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes DB record for external instance (no container)', async () => {
|
||||||
|
vi.mocked(instanceRepo.findById).mockResolvedValue(makeInstance({ containerId: null }));
|
||||||
|
|
||||||
await service.remove('inst-1');
|
await service.remove('inst-1');
|
||||||
|
|
||||||
expect(orchestrator.removeContainer).toHaveBeenCalledWith('ctr-abc', true);
|
expect(orchestrator.stopContainer).not.toHaveBeenCalled();
|
||||||
expect(instanceRepo.delete).toHaveBeenCalledWith('inst-1');
|
expect(instanceRepo.delete).toHaveBeenCalledWith('inst-1');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('removes DB record even if container is already gone', async () => {
|
it('deletes DB record even if container is already gone', async () => {
|
||||||
vi.mocked(instanceRepo.findById).mockResolvedValue({
|
vi.mocked(instanceRepo.findById).mockResolvedValue(makeInstance({ containerId: 'ctr-abc' }));
|
||||||
id: 'inst-1', containerId: 'ctr-abc', status: 'STOPPED',
|
|
||||||
serverId: 'srv-1', port: null, metadata: {},
|
|
||||||
version: 1, createdAt: new Date(), updatedAt: new Date(),
|
|
||||||
});
|
|
||||||
vi.mocked(orchestrator.removeContainer).mockRejectedValue(new Error('No such container'));
|
vi.mocked(orchestrator.removeContainer).mockRejectedValue(new Error('No such container'));
|
||||||
|
|
||||||
await service.remove('inst-1');
|
await service.remove('inst-1');
|
||||||
@@ -225,24 +237,56 @@ describe('InstanceService', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('removeAllForServer', () => {
|
||||||
|
it('stops all containers for a server', async () => {
|
||||||
|
vi.mocked(instanceRepo.findAll).mockResolvedValue([
|
||||||
|
makeInstance({ id: 'inst-1', containerId: 'ctr-1' }),
|
||||||
|
makeInstance({ id: 'inst-2', containerId: 'ctr-2' }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
await service.removeAllForServer('srv-1');
|
||||||
|
|
||||||
|
expect(orchestrator.stopContainer).toHaveBeenCalledTimes(2);
|
||||||
|
expect(orchestrator.removeContainer).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips external instances with no container', async () => {
|
||||||
|
vi.mocked(instanceRepo.findAll).mockResolvedValue([
|
||||||
|
makeInstance({ id: 'inst-1', containerId: null }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
await service.removeAllForServer('srv-1');
|
||||||
|
|
||||||
|
expect(orchestrator.stopContainer).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('inspect', () => {
|
||||||
|
it('returns container info', async () => {
|
||||||
|
vi.mocked(instanceRepo.findById).mockResolvedValue(makeInstance({ containerId: 'ctr-abc' }));
|
||||||
|
|
||||||
|
const result = await service.inspect('inst-1');
|
||||||
|
expect(orchestrator.inspectContainer).toHaveBeenCalledWith('ctr-abc');
|
||||||
|
expect(result.containerId).toBe('ctr-abc123');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws InvalidStateError when no container', async () => {
|
||||||
|
vi.mocked(instanceRepo.findById).mockResolvedValue(makeInstance({ containerId: null }));
|
||||||
|
|
||||||
|
await expect(service.inspect('inst-1')).rejects.toThrow(InvalidStateError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('getLogs', () => {
|
describe('getLogs', () => {
|
||||||
it('returns empty logs for instance without container', async () => {
|
it('returns empty logs for instance without container', async () => {
|
||||||
vi.mocked(instanceRepo.findById).mockResolvedValue({
|
vi.mocked(instanceRepo.findById).mockResolvedValue(makeInstance({ containerId: null }));
|
||||||
id: 'inst-1', containerId: null, status: 'ERROR',
|
|
||||||
serverId: 'srv-1', port: null, metadata: {},
|
|
||||||
version: 1, createdAt: new Date(), updatedAt: new Date(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await service.getLogs('inst-1');
|
const result = await service.getLogs('inst-1');
|
||||||
expect(result).toEqual({ stdout: '', stderr: '' });
|
expect(result).toEqual({ stdout: '', stderr: '' });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('returns container logs', async () => {
|
it('returns container logs', async () => {
|
||||||
vi.mocked(instanceRepo.findById).mockResolvedValue({
|
vi.mocked(instanceRepo.findById).mockResolvedValue(makeInstance({ containerId: 'ctr-abc' }));
|
||||||
id: 'inst-1', containerId: 'ctr-abc', status: 'RUNNING',
|
|
||||||
serverId: 'srv-1', port: 3000, metadata: {},
|
|
||||||
version: 1, createdAt: new Date(), updatedAt: new Date(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await service.getLogs('inst-1', { tail: 50 });
|
const result = await service.getLogs('inst-1', { tail: 50 });
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user