Files
Claude-Code-Monitor/mcp/build/tools/domains/agent-tools.js
T
nntrivi2001 8a82895c65 feat(plugins): make CCAM installable straight from a Claude Code plugin
Adds a root `ccam` plugin (`.claude-plugin/plugin.json`, `"source": "./"`) so
`/plugin marketplace add` + `/plugin install ccam@...` is enough on a machine
with nothing but Claude Code: no clone, no npm run setup, no manual npm start.

- scripts/plugin-bootstrap.js: SessionStart hook. Fast-path exit, Node >=22.5
  gate (node:sqlite), mkdir lock with stale reclaim, deps installed into
  ~/.claude/agent-dashboard/runtime/ (never the plugin cache), legacy
  checkout-hook cleanup (backed up), ~/.local/bin/ccam launcher, eager UI
  build so client routes like /run work immediately, detached server spawn.
- scripts/plugin-open.js, scripts/plugin-doctor.js: /ccam-open, /ccam-doctor.
- server/index.js: DASHBOARD_CLIENT_DIST override (plugin cache is read-only).
- mcp/build/ is committed (plugin MCP servers start before any bootstrap could
  build them) and kept honest by scripts/check-mcp-build.js (content hash,
  not mtime), enforced by pre-commit when mcp/src changes.
- plugins/ccam-dashboard/.mcp.json moved under plugins/ccam/ with a working
  ${CLAUDE_PLUGIN_ROOT} path (the old relative path never resolved from a
  marketplace-cached subdir).
- Docs: README, INSTALL, SETUP, ARCHITECTURE, CLAUDE.md, docs/PLUGINS.md,
  docs/MCP.md, docs/CLI.md, docs/HOOKS.md.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-10 16:05:37 +07:00

159 lines
8.0 KiB
JavaScript

/**
* @file agent-tools.ts
* @description Defines and registers tools for managing agents in the dashboard, including listing agents with filters, retrieving agent details, creating new agents, and updating existing agents. Each tool includes input validation using Zod schemas and interacts with the dashboard API to perform the necessary operations. The tools also check for mutation permissions before allowing changes to agent data, ensuring that the application configuration is respected.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
/* =============================================================================
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
* =============================================================================
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
*
* ## Design constraints
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
*
* ## Remote data & SSH
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
*
* ## Observability
* Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four
* provisioned boards (overview, sessions, tools, alerts). Native npm scripts and
* Docker Compose profiles are documented in `monitoring/README.md`.
*
* ## Internal dependencies
* - `../../core/tool-registry.js`
* - `../../policy/tool-guards.js`
* - `../schemas.js`
* - `../../types/tool-context.js`
*
* ## Public surface
* - `registerAgentTools` — exported API; see TSDoc on the symbol for behavior.
*
* ## Testing pointers
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
* - Server contract changes require `npm run test:server` and OpenAPI sync.
* - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
*
* ## Related docs
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
* - `docs/API.md` — REST reference.
* - `.claude/skills/file-headers/` — mandatory `@author` header policy.
* ============================================================================= */
/* -----------------------------------------------------------------------------
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
* -----------------------------------------------------------------------------
* **registerAgentTools**
* Part of this module's public contract. Downstream imports should treat
* the signature and return type as stable unless release notes say otherwise.
* When behavior changes, update the `@file` overview and relevant tests.
*
* ----------------------------------------------------------------------------- */
import { z } from "zod";
import { createToolRegistrar } from "../../core/tool-registry.js";
import { assertMutationsEnabled } from "../../policy/tool-guards.js";
import { AgentStatusSchema, JsonObjectSchema } from "../schemas.js";
/**
* Registers the four agent-management tools backing `/api/agents/*`. List/
* get are unconditional reads; create/update call
* {@link assertMutationsEnabled} first. Agents mirror Claude Code's own
* main-agent/subagent model: one main agent plus zero or more subagents
* (`type: "subagent"`, optional `subagent_type`, linked via `parent_agent_id`).
*/
export function registerAgentTools(context) {
const { api, logger, server, config } = context;
const register = createToolRegistrar(server, logger);
// Policy: none. Input: limit (1-500, default 50), offset (default 0),
// status/session_id (optional). Calls GET /api/agents?... — the dashboard
// honors only ONE of status/session_id per call (session_id wins,
// ignoring limit/offset), so passing both doesn't intersect-filter.
// Output: { agents, limit, offset }, each agent's own cost attached (from
// its metadata token buckets, not its session's total).
register("dashboard_list_agents", "List agents with optional status/session filters and pagination.", {
limit: z.number().int().min(1).max(500).optional(),
offset: z.number().int().min(0).max(100_000).optional(),
status: AgentStatusSchema.optional(),
session_id: z.string().min(1).max(256).optional(),
}, async (args) => {
const limit = args.limit ?? 50;
const offset = args.offset ?? 0;
return api.get("/api/agents", {
query: {
limit,
offset,
status: args.status,
session_id: args.session_id,
},
});
});
// Policy: none. Input: agent_id (required). Calls GET /api/agents/:id.
// Output: { agent } — 404s (ApiError, NOT_FOUND) if missing; unlike
// dashboard_list_agents, no per-agent cost is attached.
register("dashboard_get_agent", "Get a single agent by ID.", {
agent_id: z.string().min(1).max(256),
}, async (args) => {
const agentId = args.agent_id;
return api.get(`/api/agents/${encodeURIComponent(agentId)}`);
});
// Policy: MUTATIONS required. Input: id/session_id/name (required); type
// (default "main"), subagent_type, status (default "waiting"), task,
// parent_agent_id, metadata (all optional). Calls POST /api/agents.
// Output: { agent, created } — an existing id returns as-is (created: false).
register("dashboard_create_agent", "Create a new agent in a session.", {
id: z.string().min(1).max(256),
session_id: z.string().min(1).max(256),
name: z.string().min(1).max(500),
type: z.enum(["main", "subagent"]).optional(),
subagent_type: z.string().max(128).optional(),
status: AgentStatusSchema.optional(),
task: z.string().max(5000).optional(),
parent_agent_id: z.string().max(256).optional(),
metadata: JsonObjectSchema.optional(),
}, async (args) => {
assertMutationsEnabled(config);
return api.post("/api/agents", {
body: {
id: args.id,
session_id: args.session_id,
name: args.name,
type: args.type,
subagent_type: args.subagent_type,
status: args.status,
task: args.task,
parent_agent_id: args.parent_agent_id,
metadata: args.metadata,
},
});
});
// Policy: MUTATIONS required. Input: agent_id (required);
// name/status/task/current_tool/ended_at/metadata optional — current_tool
// is nullable (explicitly clearable) and preserved when omitted entirely.
// Calls PATCH /api/agents/:id. Output: { agent } — 404s if missing.
register("dashboard_update_agent", "Update an existing agent's lifecycle state and metadata.", {
agent_id: z.string().min(1).max(256),
name: z.string().max(500).optional(),
status: AgentStatusSchema.optional(),
task: z.string().max(5000).optional(),
current_tool: z.string().max(256).nullable().optional(),
ended_at: z.string().datetime().optional(),
metadata: JsonObjectSchema.optional(),
}, async (args) => {
assertMutationsEnabled(config);
const agentId = args.agent_id;
return api.patch(`/api/agents/${encodeURIComponent(agentId)}`, {
body: {
name: args.name,
status: args.status,
task: args.task,
current_tool: args.current_tool,
ended_at: args.ended_at,
metadata: args.metadata,
},
});
});
}