Docs/SDKs/TypeScript

Diaphora TypeScript SDK

TypeScript client library for the Diaphora API.

Supported Node.js versions: 20.x, 22.x

Installation

Shell
npm install diaphora-typescript

Authentication

The Diaphora client needs your Diaphora credentials. You can either pass these directly to the constructor or via environment variables.

TypeScript
import { BasicAuthenticator } from 'diaphora-typescript';

const auth = new BasicAuthenticator('user@example.com', 'your-password');

Credentials can also be provided via environment variables:

Text
DIAPHORA_USERNAME=user@example.com
DIAPHORA_PASSWORD=your-password

To use a custom auth scheme, extend DiaphoraAuthenticator:

TypeScript
import { DiaphoraAuthenticator } from 'diaphora-typescript';

class MyAuthenticator extends DiaphoraAuthenticator {
  token(): string | Promise<string> {
    return 'my-session-token';
  }
}

Setup

TypeScript
import { FragsStoreClient, FragsRouterClient } from 'diaphora-typescript';

const store = new FragsStoreClient(auth);
const router = new FragsRouterClient(auth);
ClientDescription
storePlan and result management
routerPlan execution and MCP tools

Quickstart

Search for plans

TypeScript
// namespace is one of: 'all' | 'diaphora' | 'barndoor' | 'none'
const plans = await store.searchPlans(undefined, undefined, 'diaphora');

Show a plan

TypeScript
const plan = await store.showPlan(plans[0]?.id);
console.log(plan.name, plan.description);

Create a plan

TypeScript
const newPlan = await store.createPlan({
  name: 'Daily Summary',
  description: 'Summarizes activity from the past 24 hours',
  visibility: 'organization',
  labels: ['summary', 'daily'],
  text: '<plan definition>',
});

Search results for a plan

TypeScript
const results = await store.searchResults(plan.id, undefined, 'success');

Run a plan

TypeScript
const response = await router.runPlan(plan.id, {
  parameters: { animal_type: 'feline' },
});

Stream a plan execution

TypeScript
import type { StreamEvent } from 'diaphora-typescript';

await router.streamPlan(
  plan.id,
  { parameters: { animal_type: 'feline' } },
  (event: StreamEvent) => {
    if (event.event === 'start') {
      console.log(`[${event.component}] starting...`);
    } else if (event.event === 'end') {
      console.log(`[${event.component}] done`);
    } else if (event.event === 'result') {
      const content = event.content as Record<string, unknown>;
      console.log(content.document);
    }
  }
);

store (FragsStoreClient)

Plans

MethodDescription
searchPlansSearch plans. namespace is one of 'all', 'diaphora', 'barndoor', 'none'
showPlanGet plan details
createPlanCreate a plan
updatePlanUpdate a plan
deletePlanDelete a plan
listPlanLabelsList all labels used across plans

searchPlans

Search plans visible to the authenticated user, with optional filtering and sorting.

Parameters

NameTypeRequiredDescription
labelstring[]NoFilter to plans tagged with any of the given labels
searchstringNoFull-text search string
namespace'all' | 'diaphora' | 'barndoor' | 'none'NoScope of plans to include
limitnumberNoMaximum number of results to return
offsetnumberNoNumber of results to skip (for pagination)
orderBy'name' | 'created_at' | 'updated_at'NoField to sort by
orderMode'ASC' | 'DESC'NoSort direction

Example

TypeScript
const plans = await store.searchPlans(['daily'], 'summary', 'diaphora', 10, 0, 'created_at', 'DESC');

showPlan

Get full details for a single plan, including its text and parameter definitions.

Parameters

NameTypeRequiredDescription
planIdstringYesUUID of the plan

Example

TypeScript
const plan = await store.showPlan('plan-uuid');
console.log(plan.name, plan.text);

createPlan

Create a new plan.

Parameters

NameTypeRequiredDescription
body.namestringYesDisplay name for the plan
body.descriptionstringYesHuman-readable description
body.visibility'user' | 'organization' | 'namespace'YesWho can see the plan
body.labelsstring[]YesLabels to tag the plan with
body.textstringYesThe plan definition (Frags syntax)
body.namespacestringNoNamespace to publish to (required when visibility is 'namespace')
body.document_templatestringNoGo template for the output document

Example

TypeScript
const plan = await store.createPlan({
  name: 'Daily Summary',
  description: 'Summarises activity from the past 24 hours',
  visibility: 'organization',
  labels: ['summary', 'daily'],
  text: '<plan definition>',
});

updatePlan

Replace all fields of an existing plan.

Parameters

NameTypeRequiredDescription
planIdstringYesUUID of the plan to update
body.namestringYesDisplay name for the plan
body.descriptionstringYesHuman-readable description
body.visibility'user' | 'organization' | 'namespace'YesWho can see the plan
body.labelsstring[]YesLabels to tag the plan with
body.textstringYesThe plan definition (Frags syntax)
body.namespacestringNoNamespace to publish to
body.document_templatestringNoGo template for the output document

Example

TypeScript
await store.updatePlan('plan-uuid', {
  name: 'Updated Summary',
  description: 'Now covers the past 48 hours',
  visibility: 'organization',
  labels: ['summary', 'daily'],
  text: '<updated plan definition>',
});

deletePlan

Delete a plan by ID. Returns void.

Parameters

NameTypeRequiredDescription
planIdstringYesUUID of the plan to delete

Example

TypeScript
await store.deletePlan('plan-uuid');

listPlanLabels

List all unique labels used across plans in the organization.

Example

TypeScript
const labels = await store.listPlanLabels();
console.log(labels); // ['daily', 'summary', 'report']

Results

MethodDescription
searchResultsSearch results. status is 'success' or 'error'
showResultsGet result details
createResultsCreate a result
deleteResultsDelete a result
listResultStatsGet result statistics

searchResults

Search execution results, optionally filtering by plan, status, or date range.

Parameters

NameTypeRequiredDescription
planIdstringNoFilter to results for a specific plan UUID
searchstringNoFull-text search string
status'success' | 'error'NoFilter by execution status
limitnumberNoMaximum number of results to return
offsetnumberNoNumber of results to skip (for pagination)
startDateNoReturn only results created at or after this time
endDateNoReturn only results created at or before this time

Example

TypeScript
const results = await store.searchResults(
  plan.id,
  undefined,
  'success',
  20,
  0,
  new Date('2025-01-01'),
  new Date('2025-02-01'),
);

showResults

Get full details for a single result, including the execution data.

Parameters

NameTypeRequiredDescription
resultsIdstringYesUUID of the result

Example

TypeScript
const result = await store.showResults('result-uuid');
console.log(result.data.document);

createResults

Store a result record manually, useful for persisting results generated outside the router.

Parameters

NameTypeRequiredDescription
body.plan_idstringYesUUID of the plan this result belongs to
body.plan_namestringYesName of the plan at the time of execution
body.dataobjectYesExecution response body (result, document, warnings, etc.)
body.idstringNoOptional UUID to assign to this result

Example

TypeScript
const result = await store.createResults({
  plan_id: 'plan-uuid',
  plan_name: 'Daily Summary',
  data: {
    result: {},
    document: 'Generated output here',
    warnings: [],
  },
});

deleteResults

Delete a result by ID. Returns void.

Parameters

NameTypeRequiredDescription
resultsIdstringYesUUID of the result to delete

Example

TypeScript
await store.deleteResults('result-uuid');

listResultStats

Get per-result statistics, optionally filtered to a date range.

Parameters

NameTypeRequiredDescription
startDateNoReturn only stats for results created at or after this time
endDateNoReturn only stats for results created at or before this time

Example

TypeScript
const stats = await store.listResultStats(
  new Date('2025-01-01'),
  new Date('2025-02-01'),
);
MethodDescription
listPublicLinksList public links for a result
createPublicLinkCreate a public link. expires_in accepts values like '7d' or '24h'
deletePublicLinkDelete a public link
showResultPublicLinkFetch a result via public link (no auth required)

List all public share links for a result.

Parameters

NameTypeRequiredDescription
resultsIdstringYesUUID of the result

Example

TypeScript
const links = await store.listPublicLinks('result-uuid');

Create a public share link for a result with an expiry duration and a display label.

Parameters

NameTypeRequiredDescription
resultsIdstringYesUUID of the result
body.expires_instringYesHow long until the link expires, e.g. '7d' or '24h'
body.labelstringYesHuman-readable label for this link

Example

TypeScript
const link = await store.createPublicLink('result-uuid', {
  expires_in: '7d',
  label: 'Share with client',
});
console.log(link.id, link.expires_at);

Revoke a public link. Returns void.

Parameters

NameTypeRequiredDescription
resultsIdstringYesUUID of the result
publicLinkIdstringYesUUID of the public link to revoke

Example

TypeScript
await store.deletePublicLink('result-uuid', 'link-uuid');

Fetch result details via a public link — no authentication required.

Parameters

NameTypeRequiredDescription
publicLinkIdstringYesUUID of the public link

Example

TypeScript
const result = await store.showResultPublicLink('link-uuid');
console.log(result.data.document);

Tools & Schema

MethodDescription
listToolsList available tools
showToolGet tool details
showDefaultToolsGet default tools
createToolCreate a tool
updateToolUpdate a tool
showMcpServerDetailsGet MCP server details for a tool
showApiCPServerDetailsGet API CP server details for a tool
getFragsSchemaGet the Frags JSON schema
getFragsSkillGet the Frags skill definition

listTools

List all tool configurations available to the organization.

Example

TypeScript
const tools = await store.listTools();

showTool

Get full details of a tool configuration. Facet parameters filter which MCP servers, collections, and API CPs are returned.

Parameters

NameTypeRequiredDescription
toolIdstringYesUUID of the tool
facetMcpsstring[]NoOnly include these MCP server IDs
facetCollectionsstring[]NoOnly include these collection names
facetApiCpsstring[]NoOnly include these API CP IDs

Example

TypeScript
const tool = await store.showTool('tool-uuid');
console.log(tool.mcp_servers);

showDefaultTools

Get the default tool configuration. Facet parameters work the same as showTool.

Parameters

NameTypeRequiredDescription
facetMcpsstring[]NoOnly include these MCP server IDs
facetCollectionsstring[]NoOnly include these collection names
facetApiCpsstring[]NoOnly include these API CP IDs

Example

TypeScript
const defaults = await store.showDefaultTools();

createTool

Create a new tool configuration.

Parameters

NameTypeRequiredDescription
body.namestringYesDisplay name for the tool
body.defaultbooleanYesWhether this is the default tool configuration
body.mcp_serversmcp_server[]YesMCP servers to include
body.collectionscollection[]YesCollections to include
body.api_cpsapicp_config[]YesAPI CP servers to include

Example

TypeScript
const tool = await store.createTool({
  name: 'My Tool',
  default: false,
  mcp_servers: [],
  collections: [],
  api_cps: [],
});

updateTool

Replace all fields of an existing tool configuration.

Parameters

NameTypeRequiredDescription
toolIdstringYesUUID of the tool to update
body.namestringYesDisplay name for the tool
body.defaultbooleanYesWhether this is the default tool configuration
body.mcp_serversmcp_server[]YesMCP servers to include
body.collectionscollection[]YesCollections to include
body.api_cpsapicp_config[]YesAPI CP servers to include

Example

TypeScript
await store.updateTool('tool-uuid', {
  name: 'Updated Tool',
  default: true,
  mcp_servers: [],
  collections: [],
  api_cps: [],
});

showMcpServerDetails

Get the configuration for a specific MCP server within a tool.

Parameters

NameTypeRequiredDescription
toolIdstringYesUUID of the tool
serverIdstringYesUUID of the MCP server

Example

TypeScript
const server = await store.showMcpServerDetails('tool-uuid', 'server-uuid');
console.log(server.url, server.authentication_method);

showApiCPServerDetails

Get the configuration for a specific API CP server within a tool.

Parameters

NameTypeRequiredDescription
toolIdstringYesUUID of the tool
serverIdstringYesUUID of the API CP server

Example

TypeScript
const server = await store.showApiCPServerDetails('tool-uuid', 'server-uuid');

getFragsSchema

Fetch the Frags JSON schema used to validate plan definitions.

Example

TypeScript
const schema = await store.getFragsSchema();

getFragsSkill

Fetch the Frags skill definition as a markdown string, suitable for use as an LLM system prompt.

Example

TypeScript
const skill = await store.getFragsSkill();

router (FragsRouterClient)

Plan Execution

MethodDescription
runPlanExecute a plan synchronously
streamPlanExecute a plan and receive SSE events via callback. Returns the final result.

streamPlan delivers StreamEvent objects to the callback:

event.eventAdditional fieldsDescription
'start'component, sessionA component started
'end'componentA component finished
'result'contentResult payload — content.document holds the output text

runPlan

Execute a plan synchronously and return the result once complete.

Parameters

NameTypeRequiredDescription
planIdstringYesUUID of the plan to execute
body.parametersRecord<string, unknown>NoInput parameters for the plan (defaults to {})
body.auth_overridesauth_override[]NoPer-execution token overrides for MCP/API CP servers
body.resourcesRecord<string, string>NoNamed resource bindings for the execution

Example

TypeScript
const result = await router.runPlan('plan-uuid', {
  parameters: { animal_type: 'feline' },
});
console.log(result.document);

streamPlan

Execute a plan and receive StreamEvent objects via a callback as each component starts and finishes. Returns the final result content once the stream closes, or undefined if the stream ends without a result event.

Parameters

NameTypeRequiredDescription
planIdstringYesUUID of the plan to execute
body.parametersRecord<string, unknown>NoInput parameters for the plan (defaults to {})
body.auth_overridesauth_override[]NoPer-execution token overrides for MCP/API CP servers
body.resourcesRecord<string, string>NoNamed resource bindings for the execution
onEvent(event: StreamEvent) => voidNoCallback invoked for each SSE event

Unlike runPlan, the returned promise can resolve to undefined (the stream may end without ever emitting a result event) — always guard with ?. or a null check.

Example

TypeScript
import type { StreamEvent } from 'diaphora-typescript';

const result = await router.streamPlan(
  'plan-uuid',
  { parameters: { animal_type: 'feline' } },
  (event: StreamEvent) => {
    if (event.event === 'start') {
      console.log(`[${event.component}] starting...`);
    } else if (event.event === 'result') {
      const content = event.content as Record<string, unknown>;
      console.log(content.document);
    }
  },
);
console.log(result?.document);

MCP Tools

MethodDescription
checkPlanMcpRequirementsCheck which MCP servers a plan needs and their auth status
refreshPlanMcpRequirementsForce-refresh MCP requirement status
checkToolMcpRequirementsCheck global MCP requirements
listToolCommandsList commands on an MCP server
callToolCommandExecute an MCP command
listMcpAuthCacheList cached MCP OAuth tokens
deleteMcpAuthCacheRevoke a cached MCP token
mcpCallbackHandle an OAuth redirect callback
renderTemplateRender a template

checkPlanMcpRequirements

Check which MCP and API CP servers a plan requires and whether they are currently authenticated.

Parameters

NameTypeRequiredDescription
planIdstringYesUUID of the plan

Example

TypeScript
const requirements = await router.checkPlanMcpRequirements('plan-uuid');
for (const req of requirements) {
  console.log(req.name, req.status); // 'ready' or 'not_ready'
}

refreshPlanMcpRequirements

Force-refresh the MCP requirement status for a plan, clearing any cached auth state.

Parameters

NameTypeRequiredDescription
planIdstringYesUUID of the plan

Example

TypeScript
await router.refreshPlanMcpRequirements('plan-uuid');

checkToolMcpRequirements

Check the MCP and API CP authentication status across all tool configurations globally.

Example

TypeScript
const requirements = await router.checkToolMcpRequirements();

listToolCommands

List all available commands on a specific MCP server within a tool configuration.

Parameters

NameTypeRequiredDescription
toolsIdstringYesUUID of the tool configuration
serverIdstringYesUUID of the MCP server

Example

TypeScript
const commands = await router.listToolCommands('tool-uuid', 'server-uuid');
for (const cmd of commands) {
  console.log(cmd.name, cmd.description);
}

callToolCommand

Execute a named command on an MCP server and return the result.

Parameters

NameTypeRequiredDescription
toolsIdstringYesUUID of the tool configuration
serverIdstringYesUUID of the MCP server
commandNamestringYesName of the command to execute
bodyRecord<string, unknown>YesInput arguments for the command

Example

TypeScript
const result = await router.callToolCommand(
  'tool-uuid',
  'server-uuid',
  'list_issues',
  { repo: 'my-org/my-repo' },
);

listMcpAuthCache

List currently cached MCP OAuth tokens.

Example

TypeScript
const cache = await router.listMcpAuthCache();
for (const entry of cache) {
  console.log(entry.id, entry.expiry);
}

deleteMcpAuthCache

Revoke a cached MCP OAuth token. Returns void.

Parameters

NameTypeRequiredDescription
cacheIdstringYesID of the cache entry to revoke

Example

TypeScript
await router.deleteMcpAuthCache('cache-id');

mcpCallback

Handle the OAuth redirect callback after a user completes MCP authentication in their browser. Called automatically by the OAuth flow — you typically do not need to call this directly.

Parameters

NameTypeRequiredDescription
statestringYesOAuth state parameter from the redirect URL
codestringYesAuthorization code from the redirect URL

Example

TypeScript
await router.mcpCallback(stateParam, codeParam);

renderTemplate

Render a Go template string with a provided scope object and return the result as a string.

Parameters

NameTypeRequiredDescription
body.templatestringYesGo template string, e.g. 'Hello {{ .name }}!'
body.scopeRecord<string, unknown>YesVariables available within the template

Example

TypeScript
const output = await router.renderTemplate({
  template: 'Hello {{ .name }}!',
  scope: { name: 'World' },
});
console.log(output); // 'Hello World!'