Skip to content

Written for: For developers

Call Astrato from a server

5 min read · Updated 30 Nov 2026

The SDK runs only in a browser. A script, a scheduled job or a backend queries governed data through the MCP endpoint instead, with plain HTTPS requests and no MCP client library. This page makes the first authenticated call, then runs one query against a published semantic layer and reads back the rows and the SQL the engine ran.

Before you start:

  • A personal access token (PAT) in the ASTRATO_TOKEN environment variable. Create one and set the variable without echoing it as Authentication shows. The token acts with its owner’s permissions, so keep it in trusted server-side code only.
  • The ID of a semantic layer the token’s owner can read, in ASTRATO_LAYER_ID. Queries read the layer’s published revision: changes still in the draft are not visible until someone publishes them.
  • Node 18 or later, Python 3.8 or later, or curl. None of the examples needs a package.

Examples use https://app.astrato.io/mcp. If your organization was given another Astrato origin, use that origin with the /mcp path.

Every message is one POST to /mcp with a JSON-RPC 2.0 body and these headers:

Header Value
Authorization Bearer followed by your PAT
Content-Type application/json
Accept application/json, text/event-stream
MCP-Protocol-Version 2025-06-18, the version initialize names

The Accept header must name both types, or the server answers 406 Not Acceptable. Most tools reply with a plain JSON body. The query tools reply as server-sent events: one event: message line, then a data: line that holds the same JSON-RPC reply. Read the last data: line and ignore lines that start with :, which keep a long request open.

The endpoint is stateless. It does not send an Mcp-Session-Id header, each request stands on its own, and GET and DELETE return 405 Method Not Allowed. You do not need to carry anything from one request to the next apart from your own JSON-RPC id counter.

Each script sends the same five messages: initialize, notifications/initialized, then three tools/call requests. The query names a dimension and a calculation from a TPC-H sample layer; replace them with references your own layer returns in step 4.

Terminal window
# Send one JSON-RPC message. The token reaches curl on standard input, not in its arguments.
astrato_mcp() {
curl --silent --show-error --data "$1" --config - <<CONFIG
url = "https://app.astrato.io/mcp"
header = "Authorization: Bearer ${ASTRATO_TOKEN}"
header = "Content-Type: application/json"
header = "Accept: application/json, text/event-stream"
header = "MCP-Protocol-Version: 2025-06-18"
CONFIG
}
astrato_mcp '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"my-reporting-job","version":"1.0.0"}}}'
astrato_mcp '{"jsonrpc":"2.0","method":"notifications/initialized"}'
astrato_mcp '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"astrato_get_context","arguments":{"detail":"identity"}}}'
astrato_mcp '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"astrato_data_prepare_query","arguments":{"semanticLayerId":"'"$ASTRATO_LAYER_ID"'","search":"revenue","limit":5}}}'
astrato_mcp '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"astrato_data_execute_query","arguments":{"semanticLayerId":"'"$ASTRATO_LAYER_ID"'","limit":10,"query":{"dimensions":[{"key":"region","reference":{"dimension":"Customer region"}}],"measures":[{"key":"revenue","reference":{"measure":"Revenue"}}],"orderBy":[{"reference":{"measure":"revenue"},"direction":"descending"}]}}}}'

Add --include to the function to print the status line and headers as well.

The sections below show what each message returns. Responses are trimmed where marked ….

initialize names the protocol version your code speaks and returns the server’s. Its serverInfo.version is the tool contract version, so log it: it tells you which contract a later failure ran against.

{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2025-06-18",
"capabilities": { "tools": { "listChanged": true }, "resources": { "listChanged": true } },
"serverInfo": { "name": "nash", "version": "10.66.0" },
"instructions": "You are Nash, Astrato's AI agent. …"
}
}

instructions is guidance written for AI agents and runs to tens of kilobytes. A script can ignore it. The response carries no Mcp-Session-Id header: there is no session to capture.

Send notifications/initialized with no id. It is a notification, so the server answers 202 Accepted with an empty body. Because the endpoint is stateless, a tools/call sent without the handshake is answered too. Keep the two steps anyway: they are what any MCP server expects, and they cost two short requests.

astrato_get_context with detail: "identity" returns a compact identity and the scopes the token holds. Without detail it also returns the full routing and authoring guidance, about 60 KB.

{
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [
{
"type": "text",
"text": "{\"ok\":true,\"summary\":\"Get Nash Context\",\"data\":{…}}"
}
]
}
}

Every tool result arrives this way: result.content[0].text is a JSON string. Parsed, this one reads:

{
"ok": true,
"summary": "Get Nash Context",
"data": {
"toolContract": { "version": "10.66.0", "compatibility": "semver" },
"identity": {
"source": "signed-astrato-context",
"authoritativeForSession": true,
"user": {
"id": "00000000-0000-4000-8000-000000000001",
"tenantId": "00000000-0000-4000-8000-000000000002",
"name": "Jane Doe",
"email": "jane.doe@example.com",
"role": "administrator"
}
},
"enabled": true,
"externalAuthentication": "astrato-pat",
"auth": {
"kind": "astrato-context",
"scopes": ["workspace:read", "sl:read", "data:query", "…"]
}
}
}

A PAT is given every MCP scope. What it can read and change is still limited by its owner’s role and by what has been shared with them; see MCP scopes and permissions.

astrato_data_prepare_query lists the stored dimensions and calculations of the layer’s published revision. Copy each item’s reference into the query unchanged. Pass search to rank matches for a word; omit it to list from the start, and follow nextCursor when a page carries one.

{
"ok": true,
"summary": "Found 3 stored items for “revenue”, more to follow; …",
"data": {
"scope": "semantic",
"tiers": { "storedQuestions": 16, "dimensions": 37, "calculations": 38, "rawFields": 62 },
"revision": 18,
"publishedRevision": 18,
"fields": [
{
"reference": { "measure": "Revenue" },
"fieldKey": "[calculation].[Revenue]",
"name": "Revenue",
"sourceKind": "calculation",
"roles": ["measure"],
"dataType": "float",
"carriesOwnDefinition": true,
"description": "Net revenue after discount: SUM(extended price x (1 - discount rate)) over line items.",
"definition": "SUM([Line items].[Net revenue])"
},
"…"
],
"nextCursor": "…"
}
}

A search for region returns the dimension the query below uses:

{
"reference": { "dimension": "Customer region" },
"fieldKey": "[dimension].[Customer region]",
"name": "Customer region",
"sourceKind": "dimension",
"roles": ["dimension"],
"dataType": "string",
"description": "World region of the ordering customer (5 regions)."
}

To answer from a stored business question instead, call it with scope: "questions". The MCP tools reference lists the order in which to try each tier.

astrato_data_execute_query takes the question in query and the paging arguments beside it. Each dimension and measure gets a key of your choosing, and orderBy refers to a measure by that key. limit defaults to 100 rows; continue a longer result from nextOffset.

The reply is a server-sent event:

event: message
data: {"result":{"content":[{"type":"text","text":"{\"ok\":true,\"summary\":\"Returned 5 rows across 2 columns\",…"}]},"jsonrpc":"2.0","id":4}

Parsed, the text reads:

{
"ok": true,
"summary": "Returned 5 rows across 2 columns",
"data": {
"publishedRevision": 18,
"sourceContext": {
"connection": { "connectionId": "…", "name": "Demo dataset", "driver": "snowflake" },
"defaultLocation": { "kind": "database", "value": "DEMO_DATASET", "resolvedFrom": "connection" },
"additionalLocations": [],
"scope": "query"
},
"columns": [
{
"fieldKey": "[dimension].[Customer region]",
"name": "region",
"role": "dimension",
"dataType": "string",
"selectionIdx": 0
},
{
"fieldKey": "[calculation].[Revenue]",
"name": "revenue",
"role": "measure",
"dataType": "float",
"selectionIdx": 1,
"format": { "pattern": "$#,##0" }
}
],
"rows": [
["EUROPE", 44032702326.2956],
["ASIA", 43858010644.9379],
["AMERICA", 43565312628.9458],
["AFRICA", 43488870851.6861],
["MIDDLE EAST", 43157327433.1347]
],
"rowCount": 5,
"totalRecords": 5,
"statement": "WITH v4 AS (\n SELECT -- VIEW EXPRESSION(s)\n L_EXTENDEDPRICE * (1 - L_DISCOUNT) AS e4, …",
"truncated": false,
"omittedMetadata": { "statement": false, "sourceContext": false, "queryAnalysis": false },
"queryAnalysis": "…"
}
}

rows holds one array per row, in the order of columns. statement is the SQL the engine ran against your warehouse. For this query it was:

WITH v4 AS (
SELECT -- VIEW EXPRESSION(s)
L_EXTENDEDPRICE * (1 - L_DISCOUNT) AS e4, -- EXPRESSION
L_ORDERKEY
FROM TPCH_SF1.LINEITEM
),
q1 AS (
SELECT
d1,
SUM("v4_e4") AS m1
FROM (
SELECT
"v2_R_NAME" AS d1,
"v4_e4"
FROM (
SELECT -- GRAIN Line items
v2.R_NAME AS "v2_R_NAME",
e4 AS "v4_e4" -- EXPRESSION
FROM v4
LEFT JOIN TPCH_SF1.ORDERS AS v5 ON v4.L_ORDERKEY = v5.O_ORDERKEY
LEFT JOIN TPCH_SF1.CUSTOMER AS v3 ON v5.O_CUSTKEY = v3.C_CUSTKEY
LEFT JOIN TPCH_SF1.NATION AS v1 ON v3.C_NATIONKEY = v1.N_NATIONKEY
LEFT JOIN TPCH_SF1.REGION AS v2 ON v1.N_REGIONKEY = v2.R_REGIONKEY
) AS u1
) AS u1
GROUP BY d1
)
SELECT
d1,
m1,
COUNT(*) OVER () AS rc -- RECORDS COUNT
FROM q1
ORDER BY 2 DESC NULLS LAST, 1 ASC NULLS FIRST
LIMIT 10
OFFSET 0
;

Pass dryRun: true beside query to get the SQL without running it. If the reply is too large for the response budget, the page says pageLimitedBy: "responseBudget" and omittedMetadata names what was left out; see Query response budgets and continuation.

A failure arrives in one of two places: as an HTTP status before any tool runs, or as a tool result with isError: true.

What you get Why What to do
401 with WWW-Authenticate: Bearer … The Authorization header is missing, or the token was not accepted; the body is usually empty Check the header and that the PAT has not expired or been revoked
403 {"error":"insufficient_scope",…} The token lacks a scope this tool needs; WWW-Authenticate names it Use a credential that holds that scope
403 {"error":"MCP origin is not allowed"} The request carried a browser Origin the server does not allow Call from server-side code, which sends no Origin
405 Method Not Allowed The request was a GET or DELETE Send POST
406 Not Acceptable Accept did not name both application/json and text/event-stream Send the Accept header shown above
503 with Retry-After Astrato could not be reached while the request was being set up Wait the number of seconds in Retry-After, then retry
200 with isError: true and a JSON text The tool refused: the text parses to { "ok": false, "error": "…" }, with code and status when there is a service reason Branch on code, not on the wording of error; see Results and errors
200 with isError: true and MCP error -32602 The arguments did not match the tool’s input schema; the text names the path Fix the argument the message names

Read each tool’s exact input schema with tools/list, as Get the exact input schema shows.

  • MCP tools lists every tool and its arguments.
  • Business question YAML describes the full query shape: filters, Top N, time intelligence and advanced calculations.
  • Authentication covers PAT lifetimes, revocation and the other ways to sign in.