@makeyouragent/sdk
v0.5.0
Published
Official Node.js SDK for Make Your Agent (MYA) — build AI-powered agents with knowledge bases, tool execution, and a drop-in chat widget
Readme
@makeyouragent/sdk
Official Node.js SDK for Make Your Agent — build AI-powered agents with knowledge bases, tool execution, and a drop-in chat widget.
Install
npm install @makeyouragent/sdkQuick Start
1. Set up the server proxy (your backend)
The SDK proxies browser requests through your backend so the API key stays secret.
import { createProxyHandler } from '@makeyouragent/sdk/server';
const handler = createProxyHandler({
apiKey: 'mya_live_...', // your secret API key
pathPrefix: '/mya', // strip this prefix before forwarding
});
// Express
app.all('/mya/*', (req, res) => handler(req, res));
// Fastify
fastify.all('/mya/*', (req, reply) => handler(req, reply));
// Hono / Cloudflare Workers
app.all('/mya/*', (c) => handler(c.req.raw));
// Raw Node.js
http.createServer(handler).listen(3000);2. Add the chat widget (your frontend)
One line to embed a fully functional chat UI:
<div id="chat" style="width: 400px; height: 600px;"></div>
<script type="module">
import { MakeYourAgentWidget } from '@makeyouragent/sdk/client';
MakeYourAgentWidget.init({
baseUrl: '/mya',
agentId: 'your-agent-id',
container: '#chat',
});
</script>That's it. Your users can now chat with your AI agent.
Architecture
Browser (Widget or custom UI)
|-- fetch('/mya/...') --> Your backend (proxy handler injects API key)
|-- --> api.makeyouragent.ai (service-mya)The API key never leaves your server. The browser talks to your backend, which proxies to MYA.
Server Module
For backend operations — managing agents, knowledge bases, and direct API calls.
import { MakeYourAgentServer } from '@makeyouragent/sdk/server';
const mya = new MakeYourAgentServer({
apiKey: 'mya_live_...',
});
// Create an agent
const agent = await mya.agents.create({
name: 'Support Bot',
systemPrompt: 'You are a helpful support agent.',
});
// Chat (non-streaming)
const response = await mya.chat.send(agent.id, {
message: 'What can you help me with?',
});
// response.usage -> tokens for THIS call
// response.sessionUsage -> cumulative {totals, byModel} for the whole conversation
// Chat (streaming)
const stream = mya.chat.stream(agent.id, { message: 'Hello' });
for await (const chunk of stream) {
process.stdout.write(chunk.delta);
}
// Knowledge bases
const kb = await mya.knowledgeBases.create(agent.id, {
name: 'Product Docs',
sourceType: 'MARKDOWN',
});
await mya.knowledgeBases.import(agent.id, kb.id, {
content: '# Getting Started\n\nWelcome to our product...',
title: 'Getting Started Guide',
});
// File uploads
await mya.files.upload(agent.id, pdfBuffer, { filename: 'manual.pdf' });
// Token usage (billing) — reconcile your invoice. `from`/`to` are Unix
// timestamps in seconds; returns a per-model in/out/total breakdown + totals.
const usage = await mya.usage.get({ from: 1748736000, to: 1751327999 });
console.log(usage.totals.totalTokens, usage.byModel);
// Raw request (for endpoints not covered by resource classes)
const response = await mya.request('/api/agents/agent-id/conversations/conv-id', {
method: 'GET',
});
const data = await response.json();Client Module
For browser-side usage — either the headless client or the drop-in widget.
Headless Client (custom UI)
import { MakeYourAgentClient } from '@makeyouragent/sdk/client';
const client = new MakeYourAgentClient({ baseUrl: '/mya' });
// List agents
const agents = await client.agents.list();
// Chat with inline file upload (SDK handles upload automatically)
const stream = client.chat.stream('agent-id', {
message: 'Summarize this document',
files: [fileBlob],
});
for await (const chunk of stream) {
updateUI(chunk.delta);
}Widget (drop-in UI)
import { MakeYourAgentWidget } from '@makeyouragent/sdk/client';
// Embedded mode (fills container)
MakeYourAgentWidget.init({
baseUrl: '/mya',
agentId: 'agent-id',
container: '#chat',
mode: 'embedded',
});
// Floating mode (chat bubble in corner)
MakeYourAgentWidget.init({
baseUrl: '/mya',
agentId: 'agent-id',
container: 'body',
mode: 'floating',
theme: {
primaryColor: '#6366f1',
position: 'bottom-right',
},
});Widget Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| baseUrl | string | -- | URL to your proxy endpoint (required) |
| agentId | string | -- | Agent ID to chat with (required) |
| container | string \| HTMLElement | -- | CSS selector or DOM element (required) |
| user | EndUser | -- | End-user identity (id/email/name/metadata) sent with every message |
| mode | 'embedded' \| 'floating' \| 'fullscreen' | 'embedded' | Display mode |
| theme.primaryColor | string | '#6366f1' | Primary brand color |
| theme.fontFamily | string | System font stack | Font family |
| theme.borderRadius | string | '12px' | Border radius |
| theme.position | 'bottom-right' \| 'bottom-left' | 'bottom-right' | Floating bubble position |
| labels.placeholder | string | 'Type a message...' | Input placeholder text |
| labels.title | string | 'Chat' | Header title |
| allowFileUpload | boolean | true | Show file upload button |
| allowImageUpload | boolean | true | Show image upload button |
| onMessage | (msg: ChatResponse) => void | -- | Callback after each response |
Streaming
Both server and client modules support streaming with two patterns:
// Async iterator
const stream = mya.chat.stream(agentId, { message: 'Hello' });
for await (const chunk of stream) {
console.log(chunk.delta);
}
const finalResponse = await stream.finalResponse();
// Callbacks
mya.chat.stream(agentId, { message: 'Hello' }, {
onChunk: (chunk) => console.log(chunk.delta),
onDone: (response) => console.log('Done:', response),
onError: (err) => console.error(err),
});Identify your end users
Attach an end-user identity to any chat, the same way a tracking tool's identify() call works. Pass a user object with id, email, name, and free-form metadata (plan, company, or any traits you want). MYA stores this alongside the conversation so downstream integrations can act on it: create a Pipedrive lead, open an Intercom ticket, or fire an intent rule keyed to who the user is.
Every field is optional. Send whatever you have.
// Server SDK
await mya.chat.send(agentId, {
message: 'I want to upgrade my plan',
user: {
id: 'user_8f3a',
email: '[email protected]',
name: 'Jane Doe',
metadata: { plan: 'pro', company: 'Acme Inc' },
},
});// Browser client (headless)
const stream = client.chat.stream(agentId, {
message: 'I want to upgrade my plan',
user: {
id: 'user_8f3a',
email: '[email protected]',
name: 'Jane Doe',
metadata: { plan: 'pro' },
},
});// Widget: set once, sent with every message the widget dispatches
MakeYourAgentWidget.init({
baseUrl: '/mya',
agentId: 'agent-id',
container: '#chat',
user: {
id: 'user_8f3a',
email: '[email protected]',
name: 'Jane Doe',
metadata: { plan: 'pro' },
},
});Once identity is attached, intent rules on your agent can route the conversation into your CRM or helpdesk. A "wants to upgrade" intent can push a lead into Pipedrive, and a "reports a bug" intent can open an Intercom ticket, each enriched with the user's id, email, and metadata.
Locale-aware replies
Tell the agent how to localize a turn by passing language (BCP 47), timeZone (IANA), and currency (ISO 4217) — all optional and validated server-side. The resolved locale comes back on response.metadata.effectiveLocale, so your UI can format dates and money to match. (locale still works as a free-form back-compat tag.)
const res = await mya.chat.send(agentId, {
message: 'When does my trial end and what will I pay?',
language: 'fr-FR',
timeZone: 'Europe/Paris',
currency: 'EUR',
});
res.metadata.effectiveLocale; // { language: 'fr', formattingLocale: 'fr-FR', timeZone: 'Europe/Paris' }An agent-wide default language / time zone / currency can be set in the chatbot configuration's localization block (see below).
Verified identity, idempotent turns, and action confirmation
Three optional chat fields harden agents that execute real business actions (all backward compatible):
const res = await mya.chat.send(agentId, {
message: 'Cancel order 123',
// Idempotency: retrying with the same value replays the stored turn —
// no duplicate message, no re-executed action. Response echoes it and
// sets duplicate: true on a replay.
clientMessageId: 'turn-8f3a-001',
// Verified identity (distinct from the display-only `user` traits):
// a signed end-user JWT verified against your tenant's issuer config,
// or { subject } for server-to-server assertion (needs identity:assert scope).
identity: { token: signedEndUserJwt },
});
// Consequential writes pause instead of executing:
if (res.pendingAction) {
// { id, risk: 'HIGH_WRITE', summary, details, expiresAt, allowedDecisions }
await mya.chat.send(agentId, {
conversationId: res.conversationId,
actionDecision: { pendingActionId: res.pendingAction.id, decision: 'CONFIRM' }, // or 'CANCEL'
});
}The confirmed action executes exactly once — replaying a resolved confirmation is rejected, and nothing runs until the explicit decision arrives.
Business intents and multi-turn tasks
Agents with configured business intents return structured decision metadata on every turn, and multi-turn tasks (slot collection, disambiguation) surface a redaction-safe summary:
const res = await mya.chat.send(agentId, { message: 'Cancel my subscription' });
res.metadata.intent; // { intentKey: 'cancel_subscription', mode: 'clarify', confidenceBand: 'high', ... }
res.metadata.task; // { taskId, status: 'COLLECTING', missingSlotNames: ['subscriptionId'], ... }
// Reply with the missing value (or "the second one" against presented options) to continue the task.Intent definitions, external API credentials, and entity-resolution rules are managed through admin endpoints (/api/agents/{agentId}/business-intents, /api/credentials, /api/agents/{agentId}/openapi-specs/{specId}/security-bindings, /api/agents/{agentId}/entity-resolution-rules) — see the service README for the full setup guide.
Admin, evaluation, and quality APIs
The server SDK also wraps the agent-governance surfaces, each a resource namespace on MakeYourAgentServer. All responses are fully typed.
Intent definition sets
Author business intents as a versioned set with a draft → validate → submit-review → publish → rollback lifecycle, and dry-run a draft in the sandbox before publishing. Mutations are optimistically concurrent — pass the set's current version as expectedVersion.
const draft = await mya.intentDefinitionSets.create(agentId);
await mya.intentDefinitionSets.addIntent(agentId, draft.id, {
intent: { key: 'cancel_order', name: 'Cancel order', allowedModes: ['act'] },
expectedVersion: draft.version,
});
const summary = await mya.intentDefinitionSets.validate(agentId, draft.id);
if (summary.status === 'passed') {
await mya.intentDefinitionSets.publish(agentId, draft.id, { expectedVersion: draft.version + 1 });
}
// Dry-run a single message, or a batch of up to 50 cases, against the draft
const result = await mya.intentDefinitionSets.testRun(agentId, draft.id, { message: 'cancel order 123' });Action receipts
Every consequential action the agent takes yields a redaction-safe receipt. Read a conversation's receipts, or fetch one by id. Receipts created during a turn also appear inline on response.metadata.actionReceipts.
const receipts = await mya.actionReceipts.list(agentId, conversationId);
const receipt = await mya.actionReceipts.get(agentId, receiptId);
// receipt.status -> 'SUCCEEDED' | 'AWAITING_CONFIRMATION' | 'FAILED' | ...Knowledge grounding
Documents carry typed grounding metadata (publication status, authority, effective dates, locale, regions, products). Preview how the retrieval policy resolves a query; grounded citations are attached to chat turns via response.metadata.knowledge.
await mya.knowledgeBases.import(agentId, kbId, {
content: '# Refund policy ...',
authority: 'AUTHORITATIVE',
effectiveFrom: '2026-01-01T00:00:00Z',
regions: ['US'],
});
const preview = await mya.knowledgeBases.retrievalPreview(agentId, { query: 'refund window', limit: 5 });
// preview.groundingState, preview.selected, preview.excludedChatbot configuration and capabilities
One typed, versioned configuration contract per agent (generation, context, model routing, planning). Read the stored config, update it with optimistic concurrency, resolve the effective config, or inspect capabilities. When you pass routing fields (routingEnabled, routerModel, …) to agents.create/agents.update, the returned agent carries the resulting modelRouting block and configRevision.
const { config, revision } = await mya.chatbotConfig.get(agentId);
await mya.chatbotConfig.update(agentId, {
config: { ...config, planning: { ...config.planning, enabled: true } },
expectedRevision: revision,
});
const effective = await mya.chatbotConfig.getEffective(agentId);
const { capabilities } = await mya.chatbotConfig.getCapabilities(agentId);
// Optional agent-wide locale defaults (PRD 020) — the one section with no built-in default
await mya.chatbotConfig.update(agentId, {
config: { ...config, localization: { defaultLanguage: 'de-DE', defaultTimeZone: 'Europe/Berlin', defaultCurrency: 'EUR' } },
expectedRevision: revision,
});Business scenario evaluation
Define evaluation suites of business scenarios, publish revisions, run them against the current agent, and gate-check the result against the suite's release policy.
const suite = await mya.evaluationSuites.create(agentId, { key: 'refunds', name: 'Refund flows' });
const rev = await mya.evaluationSuites.createRevision(agentId, suite.id);
await mya.evaluationSuites.updateRevision(agentId, suite.id, rev.id, {
cases: [{ caseKey: 'basic', severity: 'high', turns: [{ message: 'cancel order 1' }], expect: { mode: 'act' } }],
expectedVersion: rev.version,
});
await mya.evaluationSuites.publishRevision(agentId, suite.id, rev.id, { expectedVersion: rev.version + 1 });
const run = await mya.evaluationRuns.create(agentId, { suiteId: suite.id, runKey: 'nightly-01' });
const { gate } = await mya.evaluationRuns.gateCheck(agentId, run.id);
// gate.decision -> 'pass' | 'fail'Feedback and quality
Collect end-user feedback (idempotent + owned via requestKey), then review, label, and adjudicate it, and read recorded business-outcome facts. The closed reason-tag vocabulary is exported as FEEDBACK_REASON_TAGS.
import { FEEDBACK_REASON_TAGS } from '@makeyouragent/sdk';
await mya.feedback.submit(agentId, conversationId, {
targetType: 'message', targetId: messageId, requestKey: 'fb-1',
rating: -1, reasonTags: ['wrong_action'],
});
const queue = await mya.quality.reviewQueue(agentId);
const label = await mya.quality.createLabel(agentId, {
targetType: 'turn', targetId: turnId, expectedValues: { intentKey: 'cancel_order' },
});
await mya.quality.adjudicate(agentId, label.id, { nextState: 'CONFIRMED' });
const facts = await mya.quality.outcomes(agentId, { conversationId });Decision traces (operator diagnostics)
A redaction-safe, stage-by-stage record of how each turn's decision was made. Admin scope only — a chat-only key or end-user principal is rejected (403). Each turn's trace id is surfaced on response.metadata.traceId; list traces (without events) or fetch one with its ordered events.
const traces = await mya.decisionTraces.list(agentId, { conversationId, limit: 20 });
const trace = await mya.decisionTraces.get(agentId, traces[0].id);
// trace.status -> 'COMPLETE' | 'OPEN' | 'WAITING_ASYNC' | ...
// trace.events -> [{ sequence, stage, eventType, status, reasonCode, safePayload, ... }]Configuration
MakeYourAgentServer
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| apiKey | string | -- | Your MYA API key (required) |
| baseUrl | string | 'https://api.makeyouragent.ai' | API base URL |
| timeout | number | 30000 | Request timeout in ms |
| maxRetries | number | 3 | Max retries on 5xx errors |
createProxyHandler
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| apiKey | string | -- | Your MYA API key (required) |
| baseUrl | string | 'https://api.makeyouragent.ai' | API base URL |
| pathPrefix | string | '' | Path prefix to strip before forwarding |
MakeYourAgentClient
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| baseUrl | string | -- | URL to your proxy endpoint (required) |
Important: Tool Callback Timing
If your agent uses OpenAPI tools that call back to your server (e.g. to fetch user data), MYA executes these callbacks during the chat.send() call — not after it returns.
This means any auth context your callback endpoint needs must be set up before calling chat.send():
// CORRECT: store session before the chat call
await storeSession(userId, authToken);
const response = await mya.chat.send(agentId, { message });
// WRONG: storing after — tool callbacks will fail with 401
const response = await mya.chat.send(agentId, { message });
await storeSession(userId, authToken); // too late!Requirements
- Node.js 18+ (uses native
fetch) - Zero runtime dependencies
