# Run SQL Query — Logfire

> Executes an arbitrary SQL query against Logfire's records (unified logs + traces, one row per span) or metrics tables and returns the results. Use this for any analysis, search, or aggregation over your telemetry — recent activity, error…

- Key: `logfire-run-sql-query`
- Type: Action (Read-only)
- Version: 0.0.2
- App: Logfire (`logfire`) — https://pipedream.com/apps/logfire.md
- This page (HTML): https://pipedream.com/apps/logfire/actions/run-sql-query
- Hints: read-only · open-world
- Source: https://github.com/PipedreamHQ/pipedream/blob/master/components/logfire/actions/run-sql-query/run-sql-query.mjs

## Description

Executes an arbitrary SQL query against Logfire's `records` (unified logs + traces, one row per span) or `metrics` tables and returns the results. Use this for any analysis, search, or aggregation over your telemetry — recent activity, error hunting, latency analysis, counts, etc. To discover what columns are available before writing a query, run `SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'records'` (or `'metrics'`) with this same tool — there is no separate schema-discovery tool. Useful columns on `records` include `start_timestamp`, `span_name`, `message`, `level`, `service_name`, `duration`, `is_exception`, `exception_type`, and `exception_message`. Example — find exceptions: `SELECT span_name, exception_type, exception_message FROM records WHERE is_exception = true ORDER BY start_timestamp DESC`. Example — count by level: `SELECT level, count(*) AS n FROM records GROUP BY level ORDER BY n DESC`. After using **Record Log Entry** to write data, use this tool to confirm what was recorded. [See the SQL reference](https://pydantic.dev/docs/logfire/reference/sql/) and [query API docs](https://pydantic.dev/docs/logfire/manage/query-api/#making-direct-http-requests).

## Props

| Prop | Type | Required | Description |
|---|---|---|---|
| `sql` | `string` | Yes | The SQL query to run, e.g. SELECT start_timestamp, message, level FROM records ORDER BY start_timestamp DESC LIMIT 20. |
| `minTimestamp` | `string` | No | ISO 8601 timestamp to bound the query's start time, e.g. 2025-01-15T00:00:00Z. Defaults to 24 hours before now if not provided. |
| `maxTimestamp` | `string` | No | ISO 8601 timestamp to bound the query's end time, e.g. 2025-01-15T23:59:59Z. Defaults to now if not provided. |
| `limit` | `integer` | No | Maximum number of rows to return. Defaults to 100, max 10000. |

## Run it

**MCP**

```ts
import { Client } from "@modelcontextprotocol/sdk/client/index.js"
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
import { PipedreamClient } from "@pipedream/sdk"

const pd = new PipedreamClient({
  projectId: process.env.PIPEDREAM_PROJECT_ID!,
  clientId: process.env.PIPEDREAM_CLIENT_ID!,
  clientSecret: process.env.PIPEDREAM_CLIENT_SECRET!,
  projectEnvironment: "production",
})

const accessToken = await pd.rawAccessToken

const transport = new StreamableHTTPClientTransport(
  new URL("https://remote.mcp.pipedream.net/v3"),
  {
    requestInit: {
      headers: {
        Authorization: `Bearer ${accessToken}`,
        "x-pd-project-id": process.env.PIPEDREAM_PROJECT_ID!,
        "x-pd-environment": "production",
        "x-pd-external-user-id": "{external_user_id}", // any stable ID for this user in your system
        "x-pd-app-slug": "logfire",
      },
    },
  },
)

const mcp = new Client({ name: "my-agent", version: "1.0.0" })
await mcp.connect(transport)

const { tools } = await mcp.listTools()

// listTools() hands your model this tool's input schema, so it can
// fill the arguments itself:
const result = await mcp.callTool({
  name: "logfire-run-sql-query",
  arguments: {
    sql: "SQL Query",
    minTimestamp: "Min Timestamp",
  },
})
```

**TypeScript**

```ts
import { PipedreamClient } from "@pipedream/sdk"

const pd = new PipedreamClient({
  projectId: process.env.PIPEDREAM_PROJECT_ID!,
  clientId: process.env.PIPEDREAM_CLIENT_ID!,
  clientSecret: process.env.PIPEDREAM_CLIENT_SECRET!,
  projectEnvironment: "production",
})

const result = await pd.actions.run({
  id: "logfire-run-sql-query",
  externalUserId: "{external_user_id}", // any stable ID for this user in your system
  configuredProps: {
    logfire: { authProvisionId: "apn_xxxxxxx" },
    sql: "SQL Query",
    minTimestamp: "Min Timestamp",
  },
})

console.log(result)
```

**cURL**

```bash
curl -X POST https://api.pipedream.com/v1/connect/{project_id}/actions/run \
  -H "Content-Type: application/json" \
  -H "X-PD-Environment: production" \
  -H "Authorization: Bearer {access_token}" \
  -d '{
    "external_user_id": "{external_user_id}",
    "id": "logfire-run-sql-query",
    "configured_props": {
      "logfire": { "authProvisionId": "apn_xxxxxxx" },
      "sql": "SQL Query",
      "minTimestamp": "Min Timestamp"
    }
  }'
```

---

- App: https://pipedream.com/apps/logfire.md · All apps: https://pipedream.com/apps
