- Docs
- Manage and extend
- Developers
- AI agent development
Written for: For developers
Call Astrato from a server
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_TOKENenvironment 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.
How the endpoint answers
Section titled “How the endpoint answers”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.
Run the whole sequence
Section titled “Run the whole sequence”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.
# 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 - <<CONFIGurl = "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.
// call-astrato.mjs: needs Node 18 or later, and no packages.const MCP_URL = 'https://app.astrato.io/mcp';const token = process.env.ASTRATO_TOKEN;const layerId = process.env.ASTRATO_LAYER_ID;let nextId = 1;
async function send(message) { const response = await fetch(MCP_URL, { method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', 'MCP-Protocol-Version': '2025-06-18', }, body: JSON.stringify(message), }); const text = await response.text(); if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`); if (!text) return undefined; // a notification is answered with 202 and no body // Query tools answer as server-sent events: the reply is the last data: line. const data = text .split('\n') .filter((line) => line.startsWith('data:')) .pop(); const reply = JSON.parse(data ? data.slice(5) : text); if (reply.error) throw new Error(`JSON-RPC ${reply.error.code}: ${reply.error.message}`); return reply.result;}
const request = (method, params) => send({ jsonrpc: '2.0', id: nextId++, method, params });
async function callTool(name, args) { const result = await request('tools/call', { name, arguments: args }); const text = result.content.find((item) => item.type === 'text')?.text ?? ''; if (result.isError) throw new Error(`${name} refused: ${text}`); return JSON.parse(text);}
// 1. Initialize, then confirm it.const init = await request('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'my-reporting-job', version: '1.0.0' },});console.log('server', init.serverInfo);await send({ jsonrpc: '2.0', method: 'notifications/initialized' });
// 2. Who is this token?const context = await callTool('astrato_get_context', { detail: 'identity' });console.log('user', context.data.identity.user.email, 'scopes', context.data.auth.scopes);
// 3. Find the stored items to query.const catalogue = await callTool('astrato_data_prepare_query', { semanticLayerId: layerId, search: 'revenue', limit: 5,});for (const field of catalogue.data.fields) console.log(field.roles[0], JSON.stringify(field.reference));
// 4. Run the query, then read the rows and the SQL the engine ran.const answer = await callTool('astrato_data_execute_query', { semanticLayerId: layerId, limit: 10, query: { dimensions: [{ key: 'region', reference: { dimension: 'Customer region' } }], measures: [{ key: 'revenue', reference: { measure: 'Revenue' } }], orderBy: [{ reference: { measure: 'revenue' }, direction: 'descending' }], },});console.log(answer.data.columns.map((column) => column.name));console.table(answer.data.rows);console.log(answer.data.statement);Run it with node call-astrato.mjs.
# call_astrato.py: needs Python 3.8 or later, and no packages.import jsonimport osimport urllib.request
MCP_URL = "https://app.astrato.io/mcp"TOKEN = os.environ["ASTRATO_TOKEN"]LAYER_ID = os.environ["ASTRATO_LAYER_ID"]next_id = 1
def send(message): req = urllib.request.Request( MCP_URL, data=json.dumps(message).encode(), method="POST", headers={ "Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json", "Accept": "application/json, text/event-stream", "MCP-Protocol-Version": "2025-06-18", }, ) # urlopen raises HTTPError for a 4xx or 5xx status; its body says why. with urllib.request.urlopen(req, timeout=120) as response: text = response.read().decode() if not text: return None # a notification is answered with 202 and no body # Query tools answer as server-sent events: the reply is the last data: line. data = [line for line in text.splitlines() if line.startswith("data:")] reply = json.loads(data[-1][5:] if data else text) if "error" in reply: raise RuntimeError(f"JSON-RPC {reply['error']['code']}: {reply['error']['message']}") return reply["result"]
def request(method, params): global next_id message = {"jsonrpc": "2.0", "id": next_id, "method": method, "params": params} next_id += 1 return send(message)
def call_tool(name, arguments): result = request("tools/call", {"name": name, "arguments": arguments}) text = next((item["text"] for item in result["content"] if item["type"] == "text"), "") if result.get("isError"): raise RuntimeError(f"{name} refused: {text}") return json.loads(text)
# 1. Initialize, then confirm it.init = request( "initialize", { "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "my-reporting-job", "version": "1.0.0"}, },)print("server", init["serverInfo"])send({"jsonrpc": "2.0", "method": "notifications/initialized"})
# 2. Who is this token?context = call_tool("astrato_get_context", {"detail": "identity"})print("user", context["data"]["identity"]["user"]["email"], "scopes", context["data"]["auth"]["scopes"])
# 3. Find the stored items to query.catalogue = call_tool( "astrato_data_prepare_query", {"semanticLayerId": LAYER_ID, "search": "revenue", "limit": 5},)for field in catalogue["data"]["fields"]: print(field["roles"][0], json.dumps(field["reference"]))
# 4. Run the query, then read the rows and the SQL the engine ran.answer = call_tool( "astrato_data_execute_query", { "semanticLayerId": LAYER_ID, "limit": 10, "query": { "dimensions": [{"key": "region", "reference": {"dimension": "Customer region"}}], "measures": [{"key": "revenue", "reference": {"measure": "Revenue"}}], "orderBy": [{"reference": {"measure": "revenue"}, "direction": "descending"}], }, },)print([column["name"] for column in answer["data"]["columns"]])for row in answer["data"]["rows"]: print(row)print(answer["data"]["statement"])Run it with python call_astrato.py.
The sections below show what each message returns. Responses are trimmed where marked ….
1. Initialize
Section titled “1. Initialize”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.
2. Confirm the initialization
Section titled “2. Confirm the initialization”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.
3. Check who the token is
Section titled “3. Check who the token is”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.
4. Find what to query
Section titled “4. Find what to query”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.
5. Run the query
Section titled “5. Run the query”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: messagedata: {"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 COUNTFROM q1ORDER BY 2 DESC NULLS LAST, 1 ASC NULLS FIRSTLIMIT 10OFFSET 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.
Handle failures
Section titled “Handle failures”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.
What next
Section titled “What next”- MCP tools lists every tool and its arguments.
- Business question YAML describes the full
queryshape: filters, Top N, time intelligence and advanced calculations. - Authentication covers PAT lifetimes, revocation and the other ways to sign in.