@maton/sdk
v0.3.1
Published
Official TypeScript SDK for Maton — connect and automate 150+ apps from Node.js.
Readme
Maton TS SDK
Official TypeScript / JavaScript SDK for Maton — connect and automate apps (Gmail, Slack, GitHub, Notion, HubSpot, and more).
npm install @maton/sdk
# or
pnpm add @maton/sdk
# or
yarn add @maton/sdkQuickstart
Sign in once through the browser, then construct the client with no options:
import { login } from "@maton/sdk";
await login(); // opens a browser; stores the session locallyimport { Maton } from "@maton/sdk";
const maton = new Maton();
const conn = (await maton.connections.create({ app: "gmail" })) as { id: string };
const connectionId = conn.id;
const gmail = maton.google_mail({ connection: connectionId });
const messages = await gmail.messages.list({ q: "is:unread", maxResults: 10 });
await gmail.messages.send({
to: "[email protected]",
subject: "hi",
body: "hello",
});Authentication
login() runs an OAuth flow in your browser and stores the session locally.
Nothing else is required: the SDK signs in, renews, and signs out on its own, with
no other Maton tool involved.
import { login, logout } from "@maton/sdk";
await login(); // sign in, and make it the active session
await login({ makeActive: false }); // add a session without switching to it
await logout(); // revoke and clear the active session
await logout({ profile: "[email protected]" }); // sign one account outWhen the authorization server refuses, login() throws OAuthError — a
MatonError subclass that carries the server's own error code, so access_denied
(the user declined) is distinguishable from a misconfigured client. Everything else
that can go wrong on the way — discovery, a timeout waiting for the browser — throws
MatonError. logout() clears the local session even when the revocation call
fails, so a machine can always be signed out.
Credentials resolve in this order:
new Maton({ profile: "..." })new Maton({ apiKey: "..." })- the
MATON_API_KEYenvironment variable MATON_PROFILE- the active stored session, or the sole one when none is marked active
Explicit credentials always win over ambient machine state. Passing both profile
and apiKey is rejected as ambiguous, and a named profile that cannot be resolved
throws rather than quietly authenticating as another account.
One deliberate difference from the Maton CLI. In the CLI,
MATON_API_KEYis a global override that outranks even-p/--profile. In this SDK an explicitprofileoption outranksMATON_API_KEY, because an option written in code is a stronger signal of intent than an exported variable, and because a multi-tenant process must be able to select an account on a machine that happens to haveMATON_API_KEYset.MATON_PROFILEdoes not outrankMATON_API_KEY— between two ambient sources, the CLI's order is kept.A second one: accessor names. The CLI's subcommands are singular nouns (
maton connection list); the SDK's collections are plural (maton.connections.list()), matching the upstream APIs these accessors wrap and the TS SDKs you have most likely used. The singular spelling still resolves and returns the same object, with a one-timeDeprecationWarning; those aliases are removed in 1.0. Run Node with--throw-deprecationto turn them into errors, or--no-deprecationto mute them.
const maton = new Maton({ profile: "[email protected]" }); // a specific accountAn API key remains the right choice where a browser sign-in is impossible, such as CI:
const maton = new Maton({ apiKey: process.env.MATON_API_KEY });Where the session is stored
Session metadata goes to the typescript section of credentials.json in
~/.config/maton on macOS and Linux, or %AppData%\Maton on Windows. The file
is shared with the other Maton SDKs, while each SDK keeps independent profiles
and an independent active-profile selection. $MATON_CONFIG_DIR overrides the
directory outright, and $XDG_CONFIG_HOME/maton takes precedence over the
defaults. The tokens themselves go to the OS keyring when the optional peer is
installed:
npm install @napi-rs/keyringWithout it, tokens are written to credentials.json in plaintext at mode 0600, and
login() warns that it did so. Installing the peer is recommended on any machine
where that file is backed up or synced.
Access tokens are short-lived; the SDK renews them in-process from the stored refresh token, so a long-running client keeps working without re-authenticating.
The same pattern works for every supported app:
const slack = maton.slack({ connection: slackConnId });
await slack.messages.send({ channel: "#general", text: "deploy finished ✅" });
const gh = maton.github({ connection: ghConnId });
await gh.issues.create({
repo: "maton-ai/maton-ts",
title: "bug: ...",
body: "...",
});
const notion = maton.notion({ connection: notionConnId });
await notion.data_sources.query({
dataSourceId: "...",
filter: { property: "Status", status: { equals: "Done" } },
});
const hubspot = maton.hubspot({ connection: hubspotConnId });
await hubspot.contacts.list({ limit: 25 });Generic passthrough:
await maton.api.post("/google-mail/gmail/v1/users/me/messages/send", {
json: { raw: "..." },
connection: connectionId,
});Awaiting one of these gives the parsed body. What it actually returns is an APIPromise, which also reaches the response behind the call — the status, the headers, and the functionRunId handle into a function invocation's logs, none of which survive the parsed path:
// The raw Response, with its body still unread — nothing is parsed for you.
const res = await maton.api.post(url, { json: { name: "ada" } }).asResponse();
res.status; // 200
res.headers.get("x-function-run-id");
// Or the parsed body and the response together.
const { data, response, functionRunId, requestId } = await maton.api
.post(url, { json: { name: "ada" } })
.withResponse();Functions
A function is a Python or Node handler that Maton hosts. Code lives in immutable
versions; the active version answers requests on the function's own host, at the
url that get returns. Manage them through maton.functions, with
maton.functions.versions, maton.functions.env, maton.functions.code, and
maton.functions.runs (whose logs sub-resource reads a run's output)
sub-resources:
const fn = (await maton.functions.create({
name: "greet",
runtime: "nodejs22.x",
files: { "index.js": "exports.handler = (event) => ({ hello: 'ada' });\n" },
})) as { function_id: string };
const functionId = fn.function_id;
// # ``MATON_API_KEY`` is runtime-provided.
await maton.functions.env.create({
functionId,
env: [{ key: "API_BASE", value: "https://example.com", type: "PLAIN" }],
});
await maton.functions.env.update({ functionId, key: "API_BASE", value: "https://example.org" });
const { url } = (await maton.functions.get({ functionId })) as { url: string };
try {
const { data, functionRunId } = await maton.api
.post(url, { json: { name: "ada" } })
.withResponse();
console.log(functionRunId, data);
} catch (err) {
if (err instanceof MatonError && err.functionRunId) {
for await (const event of maton.functions.runs.logs.tail({
functionId,
runId: err.functionRunId,
})) {
process.stdout.write(String(event.message));
}
}
}
await maton.functions.update({
functionId,
files: { "index.js": "exports.handler = (event) => ({ hi: JSON.parse(event.body ?? '{}').name });\n" },
});
await maton.functions.update({ functionId, version: 1 });
await maton.functions.versions.list({ functionId });
await maton.functions.code.download({ functionId });
const runs = (await maton.functions.runs.list({ functionId, limit: 20 })) as {
runs: { run_id: string }[];
};
await maton.functions.runs.logs.list({ functionId, runId: runs.runs[0].run_id });
await maton.functions.search({ q: '"hello"', context: 2 });Handler
The runtime calls the handler with event and an optional context, and turns its return value into an HTTP response.
Event
{
"version": 1,
"rawPath": "/",
"rawQueryString": "a=1",
"cookies": ["k=v"],
"headers": { "host": "greet-a1b2c3.maton.app" },
"queryStringParameters": { "a": "1" },
"requestContext": {
"accountId": "...",
"domainName": "greet-a1b2c3.maton.app",
"domainPrefix": "greet-a1b2c3",
"http": {
"method": "POST",
"path": "/",
"protocol": "HTTP/1.1",
"sourceIp": "...",
"userAgent": "..."
},
"runId": "...",
"time": "30/Aug/2026:17:24:03 +0000",
"timeEpoch": 1788000000000
},
"body": "{\"name\":\"ada\"}",
"isBase64Encoded": false
}Context
{
"runId": "...",
"functionName": "greet",
"functionVersion": "1",
"functionId": "...",
"accountId": "...",
"memoryLimitInMB": "128"
}Response
Anything the handler returns that is not a dict carrying a statusCode key is
sent as the response body with a 200. A returned string is JSON-encoded, so
return "hello" comes back as "hello" with the quotes. To set the status or
headers, return an envelope carrying statusCode instead:
exports.handler = (event) => ({
statusCode: 201,
headers: { "content-type": "text/plain" },
body: "created",
});Triggers
const trigger = (await maton.triggers.create({
source: "github",
eventType: "pull_request.opened",
connectionId: ghConnId,
parameters: { repo: "maton-ai/cli" },
destinations: [{ url: "https://example.com/hook" }],
})) as { trigger: { trigger_id: string } };
const triggerId = trigger.trigger.trigger_id;
await maton.triggers.list({ source: "github", status: "ENABLED" });
await maton.triggers.update({ triggerId, status: "DISABLED" });
const dst = (await maton.triggers.destinations.create({
triggerId,
url: "https://example.com/hook",
})) as { destination: { destination_id: string } };
await maton.triggers.destinations.rotateSecret({
triggerId,
destinationId: dst.destination.destination_id,
});
const events = (await maton.triggers.events.list({ triggerId, limit: 20 })) as {
events: { event_id: string }[];
};
await maton.triggers.events.replay({ triggerId, eventId: events.events[0].event_id });
for await (const event of maton.triggers.events.watch({ triggerId })) {
handle(event);
}Supported apps
| App | Accessor | Highlights |
| --------------- | ----------------------- | ----------------------------------------------------- |
| Asana | maton.asana | projects, tasks, workspaces |
| GitHub | maton.github | repos, issues, PRs, releases, labels |
| Google Ads | maton.google_ads | accounts, campaigns, ad groups, ads, keywords |
| Google Calendar | maton.google_calendar | calendars, events, ACL, freebusy |
| Google Docs | maton.google_docs | documents (create / get / write) |
| Google Drive | maton.google_drive | files, drives, permissions, comments, revisions |
| Google Mail | maton.google_mail | drafts, labels, messages, threads |
| Google Sheets | maton.google_sheets | spreadsheets, sheets, values |
| Google Tasks | maton.google_tasks | tasklists, tasks |
| HubSpot | maton.hubspot | contacts, companies, deals, associations |
| Jira | maton.jira | issues, projects, transitions, comments, users |
| Linear | maton.linear | issues, projects, cycles, teams (GraphQL) |
| Microsoft Teams | maton.microsoft_teams | teams, channels, chats, messages, meetings |
| Notion | maton.notion | pages, databases, data sources, blocks, search |
| OneDrive | maton.one_drive | drives, items (upload, share, move) |
| Outlook | maton.outlook | messages, events, contacts, folders |
| Salesforce | maton.salesforce | records, query, search, composites |
| Slack | maton.slack | channels, messages, files, reactions, schedules |
| Stripe | maton.stripe | customers, charges, invoices, subscriptions, payments |
| Trello | maton.trello | boards, cards, lists, checklists, labels |
| YouTube | maton.youtube | channels, videos, playlists, comments, search |
For endpoints not yet covered by an action, use maton.api.* to reach any endpoint covered by Maton's gateway.
Reliability
Every call goes through a fetch-based client with automatic retries. The defaults are configurable on the constructor:
const maton = new Maton({
apiKey: process.env.MATON_API_KEY,
timeoutMs: 30_000, // per-request timeout, ms
maxRetries: 2, // retry attempts on transient failures
maxBackoffMs: 20_000, // cap on a single backoff sleep, ms
});Retries fire on connection errors and on 429 / 500 / 502 / 503 / 504; other 4xx/5xx surface immediately. Backoff is truncated exponential with full jitter (botocore standard mode), and honors a server-provided Retry-After header.
Errors
All failures raise a subclass of MatonError, each carrying statusCode, requestId, the parsed body, and functionRunId — set only when the failing response carried X-Function-Run-Id, in practice a function invocation:
import { Maton, MatonError, TooManyRequestsError } from "@maton/sdk";
try {
await maton.google_mail.messages.get({ messageId, connection: connectionId });
} catch (err) {
if (err instanceof TooManyRequestsError) {
console.error("slow down; retry after", err.retryAfter);
} else if (err instanceof MatonError) {
console.error(err.statusCode, err.requestId, err.body);
}
throw err;
}The hierarchy mirrors the gateway's status mapping:
| Error | HTTP status |
| --------------------------------------------- | ------------------------------------------------------- |
| AccessDeniedError | 401, 403 — bad/missing API key or insufficient scope |
| ResourceNotFoundError | 404 |
| TooManyRequestsError (carries retryAfter) | 429 |
| ValidationError | other 4xx (incl. 412 when an action needs a connection) |
| InternalServerError | 5xx or unexpected upstream response |
| APIConnectionError | transport failure / timeout (original via cause) |
A handful of apps wrap their vendor-specific error envelopes (e.g. a GraphQL errors array or a Slack ok: false payload) in a dedicated subclass, so you can catch them by app while still falling back to MatonError:
| Error | App |
| ------------------ | ------------------------- |
| GitHubError | GitHub GraphQL/API errors |
| GoogleDriveError | Google Drive API errors |
| LinearError | Linear GraphQL/API errors |
| SlackError | Slack API errors |
| StripeError | Stripe API errors |
| YouTubeError | YouTube API errors |
Development
npm install
npm run typecheck # tsc --noEmit
npm run lint # eslint
npm run test # vitest
npm run build # tsup → dist/ (ESM + CJS + .d.ts)
npm run smoke # tsx --watch scripts/smoke.ts (live, hits the real gateway)
npm run oauth:smoke # tsx scripts/oauth-smoke.ts (live, one browser sign-in)npm run oauth:smoke runs the credential lifecycle end to end against a live
deployment — sign in, check where the token landed, make read-only calls, force a
renewal, verify precedence, sign out — and needs a human once to complete the
browser sign-in. It writes to a disposable store by default, so it cannot disturb
a session you rely on. The Python SDK has the same script at
scripts/oauth_smoke.py.
npm run smoke runs scripts/smoke.ts, a live harness that exercises every
app's read paths against the real gateway — the TypeScript analog of the Python
SDK's smoke_all_apps notebook. Copy .env.example to .env.local, set
MATON_API_KEY, then uncomment the app block(s) you want to run. Destructive
calls (sends, deletes) stay commented out by default.
