@agentmc/api
v0.3.169
Published
AgentMC API SDK, docs, and CLI for AI agents
Readme
@agentmc/api
TypeScript SDK + endpoint docs + CLI for the AgentMC API.
- API domain: https://agentmc.ai
- OpenAPI source:
https://agentmc.ai/api/openapi.json - Default SDK base URL:
https://agentmc.ai/api/v1
Install
npm install @agentmc/apiWhat This Package Includes
- Fully generated, typed SDK surface from OpenAPI.
- Generated operation docs:
docs/operations/*.md,docs/operations/index.json - Per-endpoint TypeScript examples:
examples/http/*.ts - Realtime websocket notification example:
examples/realtime/subscribeToRealtimeNotifications.ts - Unified runtime program example:
examples/runtime/agentRuntimeProgram.ts - Realtime runtime example:
examples/realtime/openclawAgentRuntime.ts - CLI for operation discovery and direct API calls.
Quick Start(SDK)
import { AgentMCApi } from '@agentmc/api';
const client = new AgentMCApi({
apiKey: process.env.AGENTMC_API_KEY,
});
const result = await client.operations.listTasks({
params: {
query: {
per_page: 20,
},
},
});
if (result.error) {
console.error(result.status, result.error);
} else {
console.log(result.data);
}Auth Configuration
Supported auth schemes:
ApiKeyAuthviaX-Api-KeySessionCookieAuthvia browser session cookie
apiKey should be a host/team API key (for example cc_...).
Configure once at client creation:
const client = new AgentMCApi({
apiKey: process.env.AGENTMC_API_KEY,
});Override auth per request:
await client.request('listTasks', {
auth: {
apiKey: process.env.AGENTMC_API_KEY,
},
params: {
query: {
per_page: 20,
},
},
});API Discovery Helpers
import { operations, operationsById } from '@agentmc/api';
console.log(operations.length); // total available operations
console.log(operationsById.listTasks.path); // /tasksRuntime helpers on client:
const allOperations = client.listOperations();
const oneOperation = client.getOperation('listTasks');Realtime Notification Subscription (Agent Sessions)
Use the low-level realtime helper when you need raw session signal subscription primitives.
For full chat + runtime files + notification handling, use OpenClawAgentRuntime in the next section.
import { AgentMCApi } from '@agentmc/api';
const client = new AgentMCApi({
apiKey: process.env.AGENTMC_API_KEY,
});
const subscription = await client.subscribeToRealtimeNotifications({
agent: 42,
onReady: (session) => {
console.log(`Realtime connected for session ${session.id}`);
},
onSignal: (signal) => {
console.log('signal', signal.type, signal.id, signal.sender);
},
onNotification: ({ notification, notificationType }) => {
console.log('Notification event:', notificationType, notification);
},
onError: (error) => {
console.error('Realtime error:', error.message);
},
});
await subscription.ready;
// Keep your process alive while subscribed...
// Later, disconnect cleanly:
await subscription.disconnect();Notes:
- This helper claims a requested realtime session for the agent before opening the websocket subscription.
- If you do not pass
session, the helper picks the newest requested session returned bylistAgentRealtimeRequestedSessions. OpenClawAgentRuntimekeeps long-lived websocket subscriptions and relies on realtime fanout for chat/files/notifications routing.- In multi-agent supervisor mode, one host-level websocket transport is multiplexed across workers; requested sessions are routed to the correct worker by
agent_id. - Single-runtime heartbeat responses can also include
host_realtime; when present, the runtime uses that host-level websocket watch channel to attach new sessions immediately and downgrades API session reconciliation to a low-frequency safety poll. - Realtime transport uses the session socket metadata and signs channel subscriptions via
authenticateAgentRealtimeSocket. - Websocket reconnect automatically replays missed persisted signals (
after_idcatch-up) before resuming live delivery. Steady-state connected sessions remain websocket-authoritative; persisted-signal polling is reserved for reconnect/fallback recovery paths. - Notification API catch-up runs as a low-frequency safety poll plus realtime readiness/recovery catch-up instead of recurring heartbeat polling.
- Use
publishRealtimeMessage(...)if you need to emit your own channel events. publishRealtimeMessage(...)automatically chunks oversized channel payloads into multiple realtime signals so each signal stays within websocket broadcast limits.- Chunk envelopes include
chunk_id,chunk_index,chunk_total,chunk_encoding, andchunk_dataunder the channel payload. - Defaults:
maxPayloadBytes=9000,maxEnvelopeBytes=10000(override per call if your runtime limits differ).
- Chunk envelopes include
- For long-running runtimes, call
disconnect()during shutdown. SetautoCloseSession: trueto also close the remote session.
Unified Runtime Program (Recommended)
Use AgentRuntimeProgram to run:
- realtime websocket handling (chat/files/notifications)
- immediate startup heartbeat plus recurring heartbeat updates (
agentHeartbeat) - recurring task polling + completion (
listDueRecurringTaskRuns,completeRecurringTaskRun) - runtime health/self-heal loop
import { AgentRuntimeProgram } from '@agentmc/api';
const runtime = AgentRuntimeProgram.fromEnv(process.env);
await runtime.run();Example:
examples/runtime/agentRuntimeProgram.ts
Realtime Runtime (Advanced)
Use AgentRuntime when you only want realtime socket handling without the heartbeat/instruction supervisor.
chat.user->chat.agent.delta/chat.agent.donesnapshot.request/file.save/file.deletenotification event bridge
examples/realtime/openclawAgentRuntime.ts
CLI Runtime Command
Run the unified runtime program directly:
npx agentmc-api runtime:startCheck runtime status quickly on the server:
npx agentmc-api runtime:statusFollow live runtime logs on the server:
npx agentmc-api runtime:logsThis command pretty-prints AgentMC runtime events by default, so chat, Agent Files, and notification flows read more like:
Chat message receivedSent chat message to agentAgent finished responseSent agent reply to userAgent file snapshot requestedSaved agent fileNotification received
Recent snapshot only, without follow mode:
npx agentmc-api runtime:logs --no-followFilter down to chat/file/notification traffic:
npx agentmc-api runtime:logs --grep 'Realtime|notification|chat|file|snapshot'Raw journalctl output:
npx agentmc-api runtime:logs --rawJSON output (for scripts/monitoring):
npx agentmc-api runtime:status --jsonruntime:status now also includes:
- computed diagnostics (missing/stale status, unresolved workers, workspace/state-file issues, missing/stale/invalid heartbeats, service PID mismatch checks)
- runtime process snapshot (
pscommand line, cpu/memory %, elapsed seconds, rss/vsz) - systemd service snapshot (
systemctl show, default serviceagentmc-host) - recent runtime errors from
journalctl(default: last30minutes, max20entries)
Useful options:
--service-name <name>to inspect a different systemd unit--errors-since-minutes <minutes>to change journal lookback window--errors-limit <count>to control max error entries--no-recent-errorsto skip journal scanruntime:logs --lines <count>to change the initial tail size before live follow moderuntime:logs --since-minutes <minutes>to widen or narrow the initial journal windowruntime:logs --grep <pattern>to filter logs while followingruntime:logs --rawto bypass AgentMC pretty formatting and print raw journal lines
The runtime log stream includes supervisor lifecycle messages plus structured worker events for:
- realtime session connect/disconnect/state changes
- inbound realtime signals such as
chat.userand notification channel events - Agent Files activity such as snapshot requests and
file.save/file.delete - notification bridge runs that triggered an agent execution
- ignored/unhandled realtime messages that may explain missing behavior
Required env:
AGENTMC_API_KEY=<host-key>
Runtime defaults (no optional env overrides):
API base URL:
https://agentmc.ai/api/v1DNS result order:
ipv4firstRuntime status path:
.agentmc/runtime-status.jsonin the current working directoryHost heartbeat interval:
60sHost realtime route interval:
1000msHost realtime route limit:
100Host realtime connected reconcile poll:
60s(push events still trigger immediate routing)Agent routing: auto-detect OpenClaw agents from
~/.openclaw/openclaw.json; heartbeat auto-provisions AgentMC agents per host.Realtime worker behavior: heartbeat disabled in worker mode, websocket routing enabled, polling fallback disabled.
Keep the host API key rotated/current for the target host.
OpenClaw prompt execution uses
openclaw agent --agent <openclaw-agent> --message "<prompt>".
Keep heartbeat telemetry up to date on every send (do not hardcode stale values):
- Runtime identity and mode:
meta.runtime.name,meta.runtime.version,meta.runtime.build,meta.runtime.mode,meta.runtime_mode. - Runtime model inventory:
meta.models. - AgentMC SDK package version:
meta.agentmc_node_package_version(@agentmc/apipackage version). - Runtime behavior flags/modes when available:
meta.thinking_mode, tool availability fields. - Usage and token/context telemetry when available: token counters, cache metrics, context usage, and usage-window/day remaining fields.
- OpenClaw-specific metadata when available:
meta.openclaw_version,meta.openclaw_build. - OpenClaw current-model pointer when available:
meta.openclaw_models_status.default_model,meta.openclaw_models_status.resolved_default. - The runtime supervisor pulls these values from OpenClaw status commands (
openclaw status --json --usage, fallbackopenclaw status --json, plusopenclaw models status --json) before each heartbeat.
Host Install Script (Systemd)
Install the always-on host service:
AGENTMC_API_KEY="cc_host_key_here" \
bash scripts/install-agentmc-host.shInstall/runtime configuration uses built-in defaults; only AGENTMC_API_KEY is required.
CLI
After install, use:
npx agentmc-api list-operationsList as JSON:
npx agentmc-api list-operations --jsonShow operation metadata:
npx agentmc-api show-operation listTasksShow generated markdown docs:
npx agentmc-api show-doc listTasksCall endpoint directly:
npx agentmc-api call listTasks \
--api-key "$AGENTMC_API_KEY" \
--params '{"query":{"limit":20}}'Development
1) Install
npm install2) Sync source OpenAPI
npm run sync:specsync:spec uses a local spec fallback at ../agentmc.ai/public/openapi.json when present, otherwise it fetches https://agentmc.ai/api/openapi.json.
3) Generate typed client artifacts/docs/examples
npm run generateOutputs:
spec/openapi.filtered.jsonsrc/generated/schema.tssrc/generated/operations.tsdocs/operations/*.mddocs/operations/index.jsonexamples/http/*.ts
4) Build package
npm run buildNotes For Agent Authors
- Use
client.operations.<operationId>for named operation calls. - Use
client.request(operationId, options)for dynamic routing. - Read per-endpoint docs from
docs/operations/<operationId>.mdwhen selecting params/body fields. - Treat the generated docs/index as the operation registry:
docs/operations/index.json
