Subchapter 2.5
references/mastra-api.mdMarkdown9 KBView on GitHub
How to use the mastra api CLI to interact with Mastra servers. Prefer fast, focused commands and compact JSON projections. Treat the installed CLI and server schema as the source of truth when discovery is needed.
Use this reference when the user asks to inspect or call agents, workflows, tools, MCP servers, memory threads, traces, logs, metrics, scores, datasets, experiments, or to debug/test commands.
mastra apiThe CLI can interact with any reachable Mastra server:
http://localhost:4111 from npm run devhttps://observability.mastra.ai (auto-targeted by trace, log, score, and metric commands)For local servers, mastra api defaults to http://localhost:4111:
npx mastra api agent listFor Mastra platform or remote servers, pass --url. For the sake of brevity in examples, $MASTRA_URL is used as a placeholder for the actual server URL which you need to set yourself:
npx mastra api --url $MASTRA_URL agent listFor Factory operations, activate the mastra-factory skill first. Use the user’s actual Factory instance URL (not the platform API/dashboard URL). Explicit --url works from an empty directory. Recognized hosted Factory domains use saved mastra auth login credentials; check mastra auth whoami and offer login if needed. Custom/self-hosted deployments may use different authentication. Factory discovery uses bundled leaf contracts and root-level /web/* routes, not the runtime schema probe below.
For an unauthenticated local runtime server, verify the server once with a cheap check before resource calls:
MASTRA_URL="${MASTRA_URL:-http://localhost:4111}"
curl -fsS "$MASTRA_URL/api/system/api-schema" >/dev/nullIf $MASTRA_URL is not reachable, ask for the correct deployment URL and set --url accordingly. For authenticated targets, use a supported read-only CLI call instead of treating an unauthenticated schema-probe failure as unreachability. Let the CLI use saved login on recognized platform hosts; for custom servers, have the user configure the deployment’s approved authentication mechanism outside chat. Never request secret values in chat or inspect saved credential files.
For authenticated servers, pass repeatable headers:
npx mastra api --url "$MASTRA_URL" --header "Authorization: Bearer $TOKEN" agent listRuntime commands (agent, workflow, tool, mcp, thread, memory, dataset, experiment) resolve the target in this order:
--url <url> for an explicit remote or self-hosted server.http://localhost:4111 for a local mastra dev server..mastra-project.json for a Mastra platform project.Observability commands (trace, log, score, metric) target https://observability.mastra.ai by default instead of a project deployment URL. The CLI resolves credentials in this order:
Authorization and X-Mastra-Project-Id headers passed with --header.MASTRA_PLATFORM_ACCESS_TOKEN and MASTRA_PROJECT_ID from the environment..mastra-project.json for the project ID.For observability calls, no --url or --header is required if MASTRA_PLATFORM_ACCESS_TOKEN and MASTRA_PROJECT_ID are set, or if .mastra-project.json is present:
npx mastra api trace list '{"page":0,"perPage":10}'
npx mastra api metric namesPass --url and --header only when overriding the hosted observability target or credentials.
list X, latest X, get X, summarize recent X): infer the resource and use the fast path first.create, update, delete, run, resume, execute), unclear resource/action, failed fast path, or exact syntax requested: use narrow CLI discovery.--schema./api/system/api-schema.Start with these command groups when present; verify with mastra api --help if the group fails.
agent workflow tool mcp thread memory trace log metric score dataset experimentUse conventional list/get commands first. Keep pages small and pipe through jq immediately.
Latest item:
npx mastra api <resource> list '{"page":0,"perPage":1}' \
| jq '.data[0]'Recent items:
npx mastra api <resource> list '{"page":0,"perPage":10}' \
| jq '.data[]'When the shape is known, project only the fields needed for the task:
npx mastra api <resource> list '{"page":0,"perPage":10}' \
| jq '.data[] | {id, name, createdAt, status}'Get details:
npx mastra api <resource> get <id> \
| jq '.data'When the shape is known, project only the fields needed for the task:
npx mastra api <resource> get <id> \
| jq '.data | {id, name, createdAt, status}'If a resource does not support the conventional shape, fall back to narrow --help for that resource/action.
--pretty during exploration.jq before reading details.perPage:1 for latest and perPage:10 or less for recent lists.jq projection. Do not increase terminal output just to see more raw JSON.Use the narrowest discovery command that can answer the question. Example for traces:
npx mastra api trace --help
npx mastra api trace list --help
npx mastra api trace list --schema
npx mastra api trace query --help
npx mastra api trace query --schemaUse trace query instead of trace list when selection requires recursive predicates, metadata filters, or conditions over related spans, scores, or feedback. First use trace query --help to confirm that the installed CLI exposes the command. The inline JSON query is required, and its cursor-bearing response stays nested under data. Read trace-query.md for availability checks, the division between CLI schema discovery and canonical documentation, query construction, and pagination.
Use top-level help only when the resource is unknown:
npx mastra api --helpRead --schema output as the contract:
command: usage stringexamples: known-good examplespositionals: required path/identity argumentsinput.required: whether JSON input is requiredinput.schema: accepted CLI JSON input, including query/body fieldsschemas: raw server route schemas for deeper debuggingmastra api accepts at most one inline JSON object as input. Do not use stdin or files unless the user explicitly asks.
For non-GET routes, the CLI splits the one JSON object into query parameters and request body according to the server route schema.
Output envelopes:
{ "data": {} }
{ "data": [], "page": { "total": 0, "page": 0, "perPage": 0, "hasMore": false } }
{ "error": { "code": "...", "message": "...", "details": {} } }INVALID_JSON: fix shell quoting; input must be one JSON object.MISSING_INPUT: run the same command with --schema and supply required JSON.MISSING_ARGUMENT: provide the positional shown by --help / --schema.HTTP_ERROR: inspect error.details, then compare against --schema or route schema.REQUEST_TIMEOUT: retry with larger --timeout, especially for workflow execution.SERVER_UNREACHABLE: verify the URL and the server check. If localhost is not running, ask whether the user wants to use a Mastra platform deployment or another remote server URL.If CLI behavior seems wrong, inspect the route-derived schema manifest instead of guessing.
Find routes by path:
curl -fsS "$MASTRA_URL/api/system/api-schema" \
| jq '.routes[] | select(.path | contains("/memory"))'Inspect one route:
curl -fsS "$MASTRA_URL/api/system/api-schema" \
| jq '.routes[] | select(.method == "POST" and .path == "/tools/:toolId/execute") | {pathParamSchema, queryParamSchema, bodySchema, responseShape}'{ "data": ... } also works.trace list and trace get return lightweight payloads by default (no span input, output, attributes, or metadata). Pass --verbose to fetch full span records, or use trace span <traceId> <spanId> to fetch one specific span in full.trace query requires inline JSON, queries completed traces, and preserves its opaque cursor at data.page.next. Pass that value unchanged as page.after with the same query shape.