> ## Documentation Index
> Fetch the complete documentation index at: https://docs.anyshift.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Graph SDK

> Use the Anyshift Graph API from TypeScript applications, automation, and developer tools.

The Anyshift Graph SDK gives TypeScript applications a small, typed client for querying your infrastructure graph. Use it for dashboards, incident workflows, CI checks, deployment automation, or any service that needs direct graph answers without going through the Annie chat interface.

<Note>
  The first public SDK release is TypeScript. Python and Go SDKs will follow.
</Note>

## Install

```bash theme={null}
npm install @anyshift/graph-sdk
```

The SDK works in Node.js 18+ and modern runtimes that provide `fetch`.

## Authenticate

Create an API token in Anyshift, then pass it with the project you want to query:

```ts theme={null}
import { GraphAnswer } from "@anyshift/graph-sdk";

const graph = new GraphAnswer({
  token: process.env.ANYSHIFT_TOKEN!,
  project: process.env.ANYSHIFT_PROJECT_ID!,
});
```

By default the SDK connects to `https://graph.anyshift.io`.

## Resolve a Resource

Use `graph.resolve()` to find current resources matching a name or fragment before running a resource-scoped helper. Results are ranked deterministically and include enough identity context to distinguish resources with similar names.

```ts theme={null}
const result = await graph.resolve({ term: "checkout", limit: 10 });

if (result.intent === "resolve") {
  for (const candidate of result.resolve?.candidates ?? []) {
    console.log(candidate.name, candidate.type, candidate.namespace);
  }
}
```

Each candidate includes `id`, `anyshiftID`, `name`, `type`, `namespace`, and `cluster`. After selecting a candidate, pass its stable `id` to helpers such as `graph.connections()`, `graph.path()`, or `graph.blast()`.

Topology helpers fail closed when a fuzzy term has multiple equally authoritative matches. They do
not select the first candidate. Catch `BadQueryError`, show its bounded candidate set, and retry with
an explicit identity:

```ts theme={null}
import { BadQueryError } from "@anyshift/graph-sdk";

try {
  await graph.connections({ resource: "three-tier-app" });
} catch (error) {
  if (error instanceof BadQueryError && error.selectionCode === "ambiguous_resource") {
    console.error(error.candidates);
    // Retry after the caller selects a candidate.id.
  }
}
```

For interactive terminal discovery, use [`annie graph explore`](/pages/product/integration/cli#deterministic-infrastructure-graph-queries).

## Query the Graph

Use typed helpers for common graph questions:

```ts theme={null}
const events = await graph.events({ since: "1h", limit: 10 });
console.log(events.summary);
```

```ts theme={null}
const blast = await graph.blast({ resource: "checkout" });
console.log(blast.summary);
```

```ts theme={null}
const path = await graph.path({ from: "checkout", to: "checkout-postgres" });
console.log(path.summary);
```

## Investigate GCP Operations

Use `cloudEvents()` to retrieve one provider-native operation without conflating it with the
broader Anyshift event story:

```ts theme={null}
const result = await graph.cloudEvents({
  provider: "gcp",
  operation: "operation-123",
  diff: true,
});

if (result.intent === "cloudevents") {
  for (const event of result.cloudEvents?.items ?? []) {
    console.log({
      operation: event.correlation.providerOperationId,
      story: event.correlation.id,
      source: event.evidence.source,
      status: event.evidence.status,
    });
  }
}
```

Inspect current GCP inventory with explicit observation and IaC evidence:

```ts theme={null}
const inventory = await graph.cloudResources({
  provider: "gcp",
  lifecycle: "alive",
  maxAge: "24h",
});
```

Provider operation IDs group provider-native activity. Anyshift correlation IDs group the broader
retained story. `audit`, `snapshot`, and `reconciliation` are distinct evidence sources. Current
producers exclude provider-rejected mutations because they did not change provider state, so their
absence does not prove that no rejected calls occurred. A retained legacy row can still be
`failed`; missing outcome evidence remains `unknown`, never inferred as success. Unknown provenance
does not mean unmanaged, and unknown freshness does not mean stale.

## Render Topology

Topology queries return graph nodes and edges. Convert them to Mermaid when you want to embed a diagram in a report, pull request, runbook, or incident update:

```ts theme={null}
import { GraphAnswer, toMermaid } from "@anyshift/graph-sdk";

const graph = new GraphAnswer({
  token: process.env.ANYSHIFT_TOKEN!,
  project: process.env.ANYSHIFT_PROJECT_ID!,
});

const topology = await graph.topology({
  service: "checkout",
  level: "container",
});

console.log(toMermaid(topology));
```

Use `level: "dynamic"` to render a sequence diagram. Other topology levels render as flowcharts.

## Raw SQL

For advanced use cases, call the Graph API query endpoint directly with Anyshift graph SQL:

```ts theme={null}
const result = await graph.query(
  "SELECT * FROM connections WHERE resource = checkout"
);

console.log(result.summary);
```

Use the [Graph Query Language reference](/pages/product/integration/graph_query_language) to find every query target, filter, accepted value, alias, modifier, and valid form.

## Capabilities

The SDK covers dependency analysis, operational timelines, topology diagrams, Kubernetes safety, security exposure, observability gaps, service dependencies, and GitOps ownership.

See [Graph SDK Capabilities](/pages/product/integration/sdk_capabilities) for the developer-oriented overview, the [Graph Query Language reference](/pages/product/integration/graph_query_language) for raw query syntax, or the canonical [`CAPABILITIES.md`](https://github.com/anyshift-io/anyshift-graph-sdk/blob/main/CAPABILITIES.md) matrix in GitHub for every helper, intent, parameter family, and output category.

## Error Handling

The SDK throws typed errors for authentication, bad queries, and unexpected API responses:

```ts theme={null}
import { AuthError, BadQueryError, GraphAnswerError } from "@anyshift/graph-sdk";

try {
  await graph.query("SELECT * FROM connections WHERE resource = checkout");
} catch (error) {
  if (error instanceof AuthError) {
    // Refresh or replace the API token.
  } else if (error instanceof BadQueryError) {
    // Fix the graph SQL or helper parameters.
  } else if (error instanceof GraphAnswerError) {
    // Inspect error.status, error.code, and error.message.
  }
}
```

## Examples and Source

The SDK source, examples, and OpenAPI contract are available in the public GitHub repository: [`anyshift-io/anyshift-graph-sdk`](https://github.com/anyshift-io/anyshift-graph-sdk).

To add the same infrastructure context to a software catalog without building a custom interface, use the [Backstage integration](/pages/product/integration/backstage).

## Troubleshooting

<AccordionGroup>
  <Accordion title="401 Unauthorized">
    Check that `ANYSHIFT_TOKEN` is set and that the token has access to the selected project.
  </Accordion>

  <Accordion title="Project not found or no graph data">
    Check that `ANYSHIFT_PROJECT_ID` points to the project you intend to query and that the project has completed ingestion.
  </Accordion>

  <Accordion title="The query returns no rows">
    Start with a broader helper such as `graph.events({ since: "24h" })` or `graph.connections({ resource: "<service-name>" })`, then narrow the query once you confirm the exact service or resource name.
  </Accordion>
</AccordionGroup>
