@workhive/agent 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # @workhive/agent
2
+
3
+ Connect an AI agent to your Workhive account. Five tools, one to one with the Workhive REST API: `list_orgs`, `list_leads`, `get_lead`, `lead_report`, `add_comment`. Reads, plus comments. No texting, no stage moves.
4
+
5
+ The easiest path needs nothing from this package: Workhive runs a remote MCP server and your agent signs in with OAuth.
6
+
7
+ ## Remote (sign in, no key)
8
+
9
+ Address: `https://app.workhive.co/api/agent/v0/mcp`
10
+
11
+ - **Claude Code:** `claude mcp add --transport http workhive --scope user https://app.workhive.co/api/agent/v0/mcp`, then `/mcp` to sign in.
12
+ - **Hermes:** `hermes mcp add workhive --url https://app.workhive.co/api/agent/v0/mcp --auth oauth`
13
+ - **Claude, ChatGPT, Grok:** add a custom connector with that address and press Allow. The exact clicks are on Workhive → Settings → Agents.
14
+
15
+ ## Local (this package, with a key)
16
+
17
+ For an agent that runs on its own and cannot open a browser. Create a key in Workhive → Settings → Agents → Advanced.
18
+
19
+ ```json
20
+ {
21
+ "mcpServers": {
22
+ "workhive": {
23
+ "command": "npx",
24
+ "args": ["-y", "@workhive/agent"],
25
+ "env": { "WORKHIVE_TOKEN": "wha_live_…" }
26
+ }
27
+ }
28
+ }
29
+ ```
30
+
31
+ That is a Claude Desktop `claude_desktop_config.json` entry; other stdio hosts take the same command and env. On start the package fetches the current tool catalog from Workhive and prints one line saying which version it loaded.
32
+
33
+ ## Environment
34
+
35
+ | Variable | Required | Notes |
36
+ | --- | --- | --- |
37
+ | `WORKHIVE_TOKEN` | yes, local only | A key from Settings → Agents → Advanced. Anyone with it can act as you. |
38
+ | `WORKHIVE_API_URL` | no | Defaults to `https://app.workhive.co`. |
39
+ | `WORKHIVE_ORG_ID` | no | Pins an org when a tool call omits `org_id`. |
40
+
41
+ `org_id` is a tool argument. Agents call `list_orgs` first and never guess it.
@@ -0,0 +1,35 @@
1
+ export type AgentToolName = 'list_orgs' | 'list_leads' | 'get_lead' | 'lead_report' | 'add_comment';
2
+ export type JsonSchemaProperty = {
3
+ type: 'string' | 'integer';
4
+ description?: string;
5
+ enum?: string[];
6
+ minimum?: number;
7
+ maximum?: number;
8
+ };
9
+ export type AgentToolInputSchema = {
10
+ type: 'object';
11
+ properties: Record<string, JsonSchemaProperty>;
12
+ required?: string[];
13
+ };
14
+ export type AgentToolForward = {
15
+ method: 'GET' | 'POST';
16
+ path: string;
17
+ query?: readonly string[];
18
+ body?: readonly string[];
19
+ };
20
+ export type AgentToolSpec = {
21
+ name: AgentToolName;
22
+ description: string;
23
+ inputSchema: AgentToolInputSchema;
24
+ forward: AgentToolForward;
25
+ };
26
+ export type AgentCatalog = {
27
+ version: string;
28
+ instructions: string;
29
+ tools: readonly AgentToolSpec[];
30
+ };
31
+ export declare const TOOL_NAMES: readonly AgentToolName[];
32
+ export declare const CATALOG_VERSION = "2026-09-23";
33
+ export declare const AGENT_CATALOG: AgentCatalog;
34
+ /** Accepts only a full five-tool catalog of the shape this package understands. */
35
+ export declare function parseCatalog(value: unknown): AgentCatalog | null;
@@ -0,0 +1,116 @@
1
+ import { RULES_VERSION, renderInstructions, renderToolDescription } from './rules.js';
2
+ export const TOOL_NAMES = [
3
+ 'list_orgs', 'list_leads', 'get_lead', 'lead_report', 'add_comment',
4
+ ];
5
+ export const CATALOG_VERSION = RULES_VERSION;
6
+ const ORG_ID = {
7
+ type: 'string',
8
+ description: 'Organization UUID from list_orgs. Never guess. Optional when WORKHIVE_ORG_ID is set.',
9
+ };
10
+ const LEAD_ID = { type: 'string', description: 'Lead UUID (pipeline_cards.id)' };
11
+ const LIST_LEAD_QUERY = [
12
+ 'search', 'status', 'stalled', 'stalled_days', 'created_from', 'created_to', 'booking', 'page', 'limit',
13
+ ];
14
+ export const AGENT_CATALOG = {
15
+ version: CATALOG_VERSION,
16
+ instructions: renderInstructions(),
17
+ tools: [
18
+ {
19
+ name: 'list_orgs',
20
+ description: renderToolDescription('list_orgs'),
21
+ inputSchema: { type: 'object', properties: {} },
22
+ forward: { method: 'GET', path: '/api/agent/v0/orgs' },
23
+ },
24
+ {
25
+ name: 'list_leads',
26
+ description: renderToolDescription('list_leads'),
27
+ inputSchema: {
28
+ type: 'object',
29
+ properties: {
30
+ org_id: ORG_ID,
31
+ search: { type: 'string' },
32
+ status: { type: 'string', enum: ['potential', 'qualified', 'disqualified'] },
33
+ stalled: { type: 'string', enum: ['true', 'false'] },
34
+ stalled_days: { type: 'integer', minimum: 1, maximum: 365 },
35
+ created_from: { type: 'string', description: 'YYYY-MM-DD in org timezone' },
36
+ created_to: { type: 'string', description: 'YYYY-MM-DD in org timezone' },
37
+ booking: {
38
+ type: 'string',
39
+ enum: ['never', 'scheduled', 'held', 'cancelled'],
40
+ description: 'Consult booking state across the whole company. never = no consult was ever booked. cancelled = booked once, every booking cancelled, none held. scheduled = one is on the books. held = one happened. Use booking=never for "who never booked", not lead_report.unbooked.',
41
+ },
42
+ page: { type: 'integer', minimum: 1 },
43
+ limit: { type: 'integer', minimum: 1, maximum: 100 },
44
+ },
45
+ },
46
+ forward: { method: 'GET', path: '/api/agent/v0/leads', query: LIST_LEAD_QUERY },
47
+ },
48
+ {
49
+ name: 'get_lead',
50
+ description: renderToolDescription('get_lead'),
51
+ inputSchema: { type: 'object', properties: { org_id: ORG_ID, id: LEAD_ID }, required: ['id'] },
52
+ forward: { method: 'GET', path: '/api/agent/v0/leads/:id' },
53
+ },
54
+ {
55
+ name: 'lead_report',
56
+ description: renderToolDescription('lead_report'),
57
+ inputSchema: {
58
+ type: 'object',
59
+ properties: {
60
+ org_id: ORG_ID,
61
+ from: { type: 'string', description: 'YYYY-MM-DD' },
62
+ to: { type: 'string', description: 'YYYY-MM-DD' },
63
+ stalled_days: { type: 'integer', minimum: 1, maximum: 365 },
64
+ },
65
+ },
66
+ forward: { method: 'GET', path: '/api/agent/v0/reports/leads', query: ['from', 'to', 'stalled_days'] },
67
+ },
68
+ {
69
+ name: 'add_comment',
70
+ description: renderToolDescription('add_comment'),
71
+ inputSchema: {
72
+ type: 'object',
73
+ properties: {
74
+ org_id: ORG_ID,
75
+ id: LEAD_ID,
76
+ body: { type: 'string', description: 'Plain-text comment body' },
77
+ },
78
+ required: ['id', 'body'],
79
+ },
80
+ forward: { method: 'POST', path: '/api/agent/v0/leads/:id/comments', body: ['body'] },
81
+ },
82
+ ],
83
+ };
84
+ function isRecord(value) {
85
+ return value != null && typeof value === 'object' && !Array.isArray(value);
86
+ }
87
+ function isToolSpec(value) {
88
+ if (!isRecord(value))
89
+ return false;
90
+ const forward = value.forward;
91
+ return (typeof value.name === 'string' &&
92
+ TOOL_NAMES.includes(value.name) &&
93
+ typeof value.description === 'string' &&
94
+ isRecord(value.inputSchema) &&
95
+ value.inputSchema.type === 'object' &&
96
+ isRecord(value.inputSchema.properties) &&
97
+ isRecord(forward) &&
98
+ (forward.method === 'GET' || forward.method === 'POST') &&
99
+ typeof forward.path === 'string' &&
100
+ forward.path.startsWith('/api/agent/v0/'));
101
+ }
102
+ /** Accepts only a full five-tool catalog of the shape this package understands. */
103
+ export function parseCatalog(value) {
104
+ if (!isRecord(value))
105
+ return null;
106
+ if (typeof value.version !== 'string' || typeof value.instructions !== 'string')
107
+ return null;
108
+ if (!Array.isArray(value.tools) || value.tools.length !== TOOL_NAMES.length)
109
+ return null;
110
+ if (!value.tools.every(isToolSpec))
111
+ return null;
112
+ const names = value.tools.map((tool) => tool.name);
113
+ if (TOOL_NAMES.some((name) => !names.includes(name)))
114
+ return null;
115
+ return { version: value.version, instructions: value.instructions, tools: value.tools };
116
+ }
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
+ import { type AgentCatalog } from './catalog.js';
4
+ export declare function createAgentMcpServer(catalog?: AgentCatalog): Server;
5
+ /**
6
+ * Fetch the live catalog from the API. Any failure, any bad shape, or an older version
7
+ * yields the built-in catalog so the package always starts.
8
+ */
9
+ export declare function loadLiveCatalog(apiUrl: string, fetchImpl?: typeof fetch, timeoutMs?: number): Promise<AgentCatalog>;
10
+ export declare function startStdio(): Promise<void>;
11
+ /** True when this file is the process entry, including npx/bin symlinks. */
12
+ export declare function isMainModule(argv1?: string): boolean;
package/dist/index.js ADDED
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env node
2
+ import { realpathSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
6
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7
+ import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
8
+ import { AGENT_CATALOG, parseCatalog } from './catalog.js';
9
+ import { DEFAULT_API_URL } from './rest-client.js';
10
+ import { runTool, toolDefinitions } from './tools.js';
11
+ const CATALOG_TIMEOUT_MS = 3000;
12
+ export function createAgentMcpServer(catalog = AGENT_CATALOG) {
13
+ const server = new Server({ name: 'workhive-agent', version: catalog.version }, { capabilities: { tools: {} }, instructions: catalog.instructions });
14
+ bindToolHandlers(server, catalog);
15
+ return server;
16
+ }
17
+ function bindToolHandlers(server, catalog) {
18
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
19
+ tools: toolDefinitions(catalog),
20
+ }));
21
+ server.setRequestHandler(CallToolRequestSchema, async (request) => runTool(request.params.name, asArgs(request.params.arguments), { catalog }));
22
+ }
23
+ /**
24
+ * Fetch the live catalog from the API. Any failure, any bad shape, or an older version
25
+ * yields the built-in catalog so the package always starts.
26
+ */
27
+ export async function loadLiveCatalog(apiUrl, fetchImpl = fetch, timeoutMs = CATALOG_TIMEOUT_MS) {
28
+ const controller = new AbortController();
29
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
30
+ try {
31
+ const url = new URL('/api/agent/v0/catalog', `${apiUrl.replace(/\/+$/, '')}/`);
32
+ const res = await fetchImpl(url.toString(), { signal: controller.signal, headers: { Accept: 'application/json' } });
33
+ if (!res.ok)
34
+ return AGENT_CATALOG;
35
+ const parsed = parseCatalog(await res.json());
36
+ if (!parsed || parsed.version < AGENT_CATALOG.version)
37
+ return AGENT_CATALOG;
38
+ return parsed;
39
+ }
40
+ catch {
41
+ return AGENT_CATALOG;
42
+ }
43
+ finally {
44
+ clearTimeout(timer);
45
+ }
46
+ }
47
+ function asArgs(value) {
48
+ return isPlainObject(value) ? value : {};
49
+ }
50
+ function isPlainObject(value) {
51
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
52
+ }
53
+ export async function startStdio() {
54
+ const apiUrl = process.env.WORKHIVE_API_URL?.trim() || DEFAULT_API_URL;
55
+ const catalog = await loadLiveCatalog(apiUrl);
56
+ const source = catalog === AGENT_CATALOG ? 'built-in' : 'live';
57
+ const server = createAgentMcpServer(catalog);
58
+ console.error(`workhive-agent running on stdio (catalog ${catalog.version}, ${source})`);
59
+ await server.connect(new StdioServerTransport());
60
+ }
61
+ /** True when this file is the process entry, including npx/bin symlinks. */
62
+ export function isMainModule(argv1 = process.argv[1]) {
63
+ if (!argv1)
64
+ return false;
65
+ try {
66
+ return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(argv1);
67
+ }
68
+ catch {
69
+ return fileURLToPath(import.meta.url) === resolve(argv1);
70
+ }
71
+ }
72
+ if (isMainModule()) {
73
+ startStdio().catch((err) => {
74
+ console.error(err);
75
+ process.exit(1);
76
+ });
77
+ }
@@ -0,0 +1,31 @@
1
+ type QueryValue = string | number | boolean | undefined;
2
+ type AgentRequestOptions = {
3
+ path: string;
4
+ method?: 'GET' | 'POST';
5
+ orgId?: string;
6
+ query?: Record<string, QueryValue>;
7
+ body?: unknown;
8
+ };
9
+ type RestErrorFields = {
10
+ error: string;
11
+ code: string;
12
+ requestId?: string;
13
+ };
14
+ export declare class AgentRestError extends Error {
15
+ readonly status: number;
16
+ readonly error: string;
17
+ readonly code: string;
18
+ readonly requestId?: string;
19
+ constructor(input: RestErrorFields & {
20
+ status: number;
21
+ });
22
+ }
23
+ /** Where the package talks when nobody says otherwise. Overridden by WORKHIVE_API_URL or config.apiUrl. */
24
+ export declare const DEFAULT_API_URL = "https://app.workhive.co";
25
+ export type AgentRestConfig = {
26
+ apiUrl?: string;
27
+ token?: string;
28
+ requestId?: string;
29
+ };
30
+ export declare function agentRequest(options: AgentRequestOptions, config?: AgentRestConfig): Promise<unknown>;
31
+ export {};
@@ -0,0 +1,95 @@
1
+ export class AgentRestError extends Error {
2
+ status;
3
+ error;
4
+ code;
5
+ requestId;
6
+ constructor(input) {
7
+ super(formatRestError(input));
8
+ this.name = 'AgentRestError';
9
+ this.status = input.status;
10
+ this.error = input.error;
11
+ this.code = input.code;
12
+ this.requestId = input.requestId;
13
+ }
14
+ }
15
+ function formatRestError(input) {
16
+ return JSON.stringify({
17
+ error: input.error,
18
+ code: input.code,
19
+ ...(input.requestId ? { requestId: input.requestId } : {}),
20
+ });
21
+ }
22
+ /** Where the package talks when nobody says otherwise. Overridden by WORKHIVE_API_URL or config.apiUrl. */
23
+ export const DEFAULT_API_URL = 'https://app.workhive.co';
24
+ export async function agentRequest(options, config = {}) {
25
+ const { apiUrl, token } = readRestConfig(config);
26
+ const headers = buildHeaders(token, options);
27
+ if (config.requestId)
28
+ headers['x-request-id'] = config.requestId;
29
+ const res = await fetch(buildUrl(apiUrl, options.path, options.query), {
30
+ method: options.method ?? 'GET',
31
+ headers,
32
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
33
+ });
34
+ const text = await res.text();
35
+ if (!res.ok)
36
+ throw toRestError(res.status, text);
37
+ if (!text)
38
+ return null;
39
+ const parsed = JSON.parse(text);
40
+ return parsed;
41
+ }
42
+ function readRestConfig(config, env = process.env) {
43
+ const apiUrl = (config.apiUrl?.trim() || env.WORKHIVE_API_URL?.trim() || DEFAULT_API_URL).replace(/\/+$/, '');
44
+ const token = (config.token ?? env.WORKHIVE_TOKEN)?.trim();
45
+ if (!token)
46
+ throw new Error('WORKHIVE_TOKEN is required');
47
+ return { apiUrl, token };
48
+ }
49
+ function buildHeaders(token, options) {
50
+ const headers = {
51
+ Accept: 'application/json',
52
+ Authorization: `Bearer ${token}`,
53
+ };
54
+ if (options.orgId)
55
+ headers['X-Workhive-Org-Id'] = options.orgId;
56
+ if (options.body !== undefined)
57
+ headers['Content-Type'] = 'application/json';
58
+ return headers;
59
+ }
60
+ function buildUrl(apiUrl, path, query) {
61
+ const url = new URL(path, `${apiUrl}/`);
62
+ for (const [key, value] of Object.entries(query ?? {})) {
63
+ if (value == null || value === '')
64
+ continue;
65
+ url.searchParams.set(key, String(value));
66
+ }
67
+ return url.toString();
68
+ }
69
+ function toRestError(status, text) {
70
+ const body = parseJsonObject(text);
71
+ return new AgentRestError({
72
+ status,
73
+ error: stringField(body, 'error') || text || 'Request failed',
74
+ code: stringField(body, 'code') || 'INTERNAL_ERROR',
75
+ requestId: stringField(body, 'requestId'),
76
+ });
77
+ }
78
+ function parseJsonObject(text) {
79
+ try {
80
+ return asPlainObject(JSON.parse(text));
81
+ }
82
+ catch {
83
+ return null;
84
+ }
85
+ }
86
+ function asPlainObject(value) {
87
+ return isPlainObject(value) ? value : null;
88
+ }
89
+ function isPlainObject(value) {
90
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
91
+ }
92
+ function stringField(body, key) {
93
+ const value = body?.[key];
94
+ return typeof value === 'string' && value ? value : undefined;
95
+ }
@@ -0,0 +1,17 @@
1
+ import type { AgentToolName } from './catalog.js';
2
+ /** Bump when any rule text changes. Served as rules_version on list_orgs and in the catalog. */
3
+ export declare const RULES_VERSION = "2026-09-23";
4
+ export declare function renderInstructions(): string;
5
+ export declare function renderToolDescription(name: AgentToolName): string;
6
+ export declare function renderSkillMarkdown(): string;
7
+ export declare function renderConnectPrompt(input: {
8
+ token: string;
9
+ origin: string;
10
+ }): string;
11
+ /**
12
+ * The paste-once prompt on Settings → Agents. Carries no key: an agent in a chat app signs in
13
+ * with OAuth; an unattended agent asks the owner for a key. Under 2000 characters.
14
+ */
15
+ export declare function renderUniversalPrompt(input: {
16
+ origin: string;
17
+ }): string;
package/dist/rules.js ADDED
@@ -0,0 +1,134 @@
1
+ /** Bump when any rule text changes. Served as rules_version on list_orgs and in the catalog. */
2
+ export const RULES_VERSION = '2026-09-23';
3
+ const FLOW = 'Workhive: you are a client of the owner\'s CRM, not the in-app SDR. ' +
4
+ 'First call list_orgs; read terms and rules_version. Never guess org_id. ' +
5
+ 'Speak terms.singular / terms.count_noun / terms.nav_label; call a booked consult what terms.home_appts_label says. ' +
6
+ 'Default briefing = lead_report. Who never booked = list_leads booking=never (whole company), then booking=cancelled as a second line. ' +
7
+ 'The only write is add_comment, and only when asked.';
8
+ const DETAIL = [
9
+ 'lead_report: New = created in the period. Stalled = whole company, untouched N days. No next step and Unbooked are among New only. Unbooked is not "everyone who never booked." Never answer that from lead_report.unbooked.',
10
+ 'booking_state is status only: scheduled may have no next_meeting when a past meeting was never closed out; say "on the books" and do not invent a date.',
11
+ 'Say potential/qualified/disqualified only if terms.show_status. Mention ballpark only if terms.show_ballpark. owner and setter are the role words. Say pipeline.name without adding the word pipeline.',
12
+ 'No SMS, no stage moves, no phone changes: say those are not available yet. Never invent a call, text or visit.',
13
+ 'Lead id is a UUID. Use only these tools; do not call dashboard routes.',
14
+ 'Errors: UNAUTHORIZED = key wrong or revoked. FORBIDDEN = not a member of that company. Empty list_orgs = this key has no company.',
15
+ 'Mention time_zone and truncated when the API returns them. Answer in markdown, counts first.',
16
+ ];
17
+ export function renderInstructions() {
18
+ return `${FLOW}\n${DETAIL.join('\n')}`;
19
+ }
20
+ const DESCRIPTIONS = {
21
+ list_orgs: 'Call this first. Lists the companies this key belongs to, each with org_type, terms (the words the screen uses) and time_zone; the response carries rules_version. Never guess org_id: use an id from here. Speak terms.singular, not the tool name.',
22
+ list_leads: 'List open leads for an org. Maps to GET /api/agent/v0/leads. Filter booking=never for leads that never booked a consult (whole company, exact total); booking=cancelled = booked once, every booking cancelled.',
23
+ get_lead: 'Get one lead by UUID, including closed ones. Maps to GET /api/agent/v0/leads/:id.',
24
+ lead_report: 'New / stalled / no next step / unbooked briefing. New is the period (default week-to-date); stalled is the whole company; the other two are among new only. Maps to GET /api/agent/v0/reports/leads.',
25
+ add_comment: 'Add a plain-text comment on a lead, authored as the owner. Only if the owner asked for it. Maps to POST /api/agent/v0/leads/:id/comments.',
26
+ };
27
+ export function renderToolDescription(name) {
28
+ return DESCRIPTIONS[name];
29
+ }
30
+ export function renderSkillMarkdown() {
31
+ return [
32
+ '---',
33
+ 'name: workhive',
34
+ 'description: Use when querying Workhive leads via Agent Kernel v0 (Claude Code, Claude Desktop, Grok, Hermes) — list orgs, lead reports, lead detail, who never booked, and optional comments. Never guess org_id; authenticate with wha_live_ PAT only.',
35
+ '---',
36
+ '',
37
+ '# Workhive Agent Kernel (v0)',
38
+ '',
39
+ `Generated from the agent rules, version ${RULES_VERSION}. Do not edit by hand; run \`npx tsx scripts/agent/render-skill.ts\`.`,
40
+ 'The server sends the current rules on every connection (instructions and tool descriptions); when this file and the server disagree, the server\'s copy wins.',
41
+ '',
42
+ '## First, every session',
43
+ '',
44
+ '1. Connect with `wha_live_…` (PAT). Do not use the website cookie/session.',
45
+ '2. Call `list_orgs`. Read `terms` and `rules_version` before you speak.',
46
+ '3. Follow the server\'s instructions and tool descriptions. The snapshot below is the same text.',
47
+ '',
48
+ '## Rules (snapshot)',
49
+ '',
50
+ ...renderInstructions().split('\n').map((line) => `- ${line}`),
51
+ '- Read `terms` before you speak: call the records `terms.singular` / `terms.count_noun` / `terms.nav_label`; call a booked visit what `terms.home_appts_label` says; call the later board `terms.move_to_pipeline_label` exactly. Never say potential, qualified, or disqualified unless `terms.show_status` is true (`show_status`). Never mention ballpark unless `terms.show_ballpark` is true (`show_ballpark`).',
52
+ '- Never guess `org_id`. If the user names a company, call `list_orgs` and match `name`; if zero or multiple matches, ask.',
53
+ '- Who never booked = `list_leads` with `booking=never`, then `booking=cancelled` as a second line. Never answer this from `lead_report.unbooked`. Unbooked is not "everyone who never booked."',
54
+ '- No next step and Unbooked are **among new** this period, not every open record. Stalled is the whole company.',
55
+ '',
56
+ '## Tools (five verbs only)',
57
+ '',
58
+ '| Tool | Purpose |',
59
+ '| --- | --- |',
60
+ '| `list_orgs` | Resolve the user\'s org(s). Call before org-scoped tools. |',
61
+ '| `list_leads` | List open leads for an `org_id` (filters optional). `booking=never` = never booked a consult, whole company. |',
62
+ '| `get_lead` | Fetch one lead by UUID. |',
63
+ '| `lead_report` | Period report: new / stalled / no_next_step / unbooked (the last two among new). |',
64
+ '| `add_comment` | Post a plain-text comment on a lead (only if asked). |',
65
+ '',
66
+ '## Auth / config',
67
+ '',
68
+ '- `WORKHIVE_TOKEN` = PAT `wha_live_…` from Settings → Agent access (not a website session).',
69
+ '- `WORKHIVE_API_URL` = API base (e.g. `https://app.workhive.co`). The package fetches the live catalog from `/api/agent/v0/catalog` on start.',
70
+ '- Optional `WORKHIVE_ORG_ID` pins a default; if the prompt names an org, still call `list_orgs` and match.',
71
+ '',
72
+ ].join('\n');
73
+ }
74
+ export function renderConnectPrompt(input) {
75
+ const origin = input.origin.replace(/\/$/, '');
76
+ const base = `${origin}/api/agent/v0`;
77
+ return [
78
+ 'You are connecting to Workhive as me. Do not log into the website.',
79
+ '',
80
+ `Key: ${input.token}`,
81
+ `API: ${base}`,
82
+ 'On every request send header: Authorization: Bearer <the key>',
83
+ '',
84
+ 'If you already have Workhive tools named list_orgs, list_leads, get_lead, lead_report, or add_comment, use those.',
85
+ `If you can add a remote MCP connector by URL, add ${base}/mcp and sign in when asked; then use those tools.`,
86
+ 'Otherwise call these HTTP endpoints and parse JSON:',
87
+ '',
88
+ `1. GET ${base}/orgs`,
89
+ ' List my companies. Never guess org_id — use an id from this list. Read terms and rules_version.',
90
+ `2. GET ${base}/reports/leads?org_id=ORG_ID`,
91
+ ' Default briefing. Before you answer, read terms on GET /orgs.',
92
+ `3. GET ${base}/leads?org_id=ORG_ID`,
93
+ ' Full list — only if I ask for every lead.',
94
+ ' Add &booking=never for everyone who never booked a consult (whole company, exact total). &booking=cancelled = booked once, all cancelled.',
95
+ `4. GET ${base}/leads/LEAD_ID?org_id=ORG_ID`,
96
+ ' One lead. LEAD_ID is a UUID.',
97
+ `5. POST ${base}/leads/LEAD_ID/comments?org_id=ORG_ID`,
98
+ ' Body: {"body":"plain text"}. Only if I ask you to comment. Never invent a call, SMS, or visit.',
99
+ '',
100
+ 'Rules:',
101
+ '- You are a client of Workhive, not the in-app SDR.',
102
+ '- You may only write comments. No SMS, no stage moves, no phone changes. If I ask, say that is not available yet.',
103
+ '- Speak terms from GET /orgs: terms.nav_label, terms.singular, terms.home_appts_label, terms.move_to_pipeline_label. Do not say "lead" when terms.singular is "Quote Request". Mention status only if terms.show_status is true. Mention ballpark only if terms.show_ballpark is true.',
104
+ '- New and Stalled: new is the period, stalled is the whole company. No next step and Unbooked are among NEW this period, not every open record. Unbooked is not everyone who never booked.',
105
+ "- Who never booked = GET /leads?booking=never, not the report's Unbooked. Call the consult what terms.home_appts_label calls it.",
106
+ '- Answer in markdown: counts first, then New / Stalled / No next step / Unbooked with contact, stage, and dates. Mention timezone and truncated if the API says so.',
107
+ '- Empty orgs list means this key has no company. 401 means the key is wrong. 403 means not a member of that company.',
108
+ '',
109
+ "Start now: list my companies, read terms, then this period's briefing — what's new, what's stalled, who has no next step.",
110
+ ].join('\n');
111
+ }
112
+ /**
113
+ * The paste-once prompt on Settings → Agents. Carries no key: an agent in a chat app signs in
114
+ * with OAuth; an unattended agent asks the owner for a key. Under 2000 characters.
115
+ */
116
+ export function renderUniversalPrompt(input) {
117
+ const origin = input.origin.replace(/\/+$/, '');
118
+ const address = `${origin}/api/agent/v0/mcp`;
119
+ return [
120
+ `You are connecting to Workhive as me. The Workhive server is ${address}. The rules for using it arrive with the connection; you do not need to remember anything from this message.`,
121
+ '',
122
+ 'If you can run commands on this computer, set yourself up now and confirm:',
123
+ `- Claude Code: run \`claude mcp add --transport http workhive --scope user ${address}\`, then tell me to type /mcp to sign in.`,
124
+ `- Hermes: run \`hermes mcp add workhive --url ${address} --auth oauth\`.`,
125
+ '- Any other local agent: run `npx -y @workhive/agent` with WORKHIVE_TOKEN set to a key from Workhive Settings, Agents, Advanced. Ask me for the key; never guess one.',
126
+ '',
127
+ 'If you cannot run commands, tell me the one step for the app I am in, then wait for me:',
128
+ '- Claude: Customize, Add connector, Add custom connector, paste the address above, press Allow when Workhive asks.',
129
+ '- ChatGPT: turn on Developer mode under Security and login, then Plugins, the plus button, Create app, paste the address above.',
130
+ '- Grok: Connectors, New Connector, Custom, paste the address above.',
131
+ '',
132
+ 'Either way, finish by calling list_orgs. Read terms and rules_version. Then say only: "Ready. Workhive is connected as <company name>."',
133
+ ].join('\n');
134
+ }
@@ -0,0 +1,18 @@
1
+ import { type AgentCatalog, type AgentToolSpec } from './catalog.js';
2
+ import { type AgentRestConfig } from './rest-client.js';
3
+ type ToolArgs = Record<string, unknown>;
4
+ export type AgentToolDefinition = Pick<AgentToolSpec, 'name' | 'description' | 'inputSchema'>;
5
+ export type ToolResult = {
6
+ content: Array<{
7
+ type: 'text';
8
+ text: string;
9
+ }>;
10
+ isError?: boolean;
11
+ };
12
+ export type ToolRunConfig = AgentRestConfig & {
13
+ catalog?: AgentCatalog;
14
+ };
15
+ export declare function toolDefinitions(catalog?: AgentCatalog): AgentToolDefinition[];
16
+ export declare const TOOL_DEFINITIONS: AgentToolDefinition[];
17
+ export declare function runTool(name: string, args?: ToolArgs, config?: ToolRunConfig): Promise<ToolResult>;
18
+ export {};
package/dist/tools.js ADDED
@@ -0,0 +1,73 @@
1
+ import { AGENT_CATALOG, TOOL_NAMES } from './catalog.js';
2
+ import { AgentRestError, agentRequest } from './rest-client.js';
3
+ const MISSING_ORG_MESSAGE = 'org_id is required. Call list_orgs to resolve the organization and pass org_id; do not guess.';
4
+ export function toolDefinitions(catalog = AGENT_CATALOG) {
5
+ return catalog.tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema }));
6
+ }
7
+ export const TOOL_DEFINITIONS = toolDefinitions();
8
+ export async function runTool(name, args = {}, config = {}) {
9
+ const catalog = config.catalog ?? AGENT_CATALOG;
10
+ const spec = catalog.tools.find((tool) => tool.name === name);
11
+ if (!spec || !TOOL_NAMES.includes(name))
12
+ return fail(`Unknown tool: ${name}`);
13
+ try {
14
+ const data = await agentRequest(toRequest(spec, args), config);
15
+ return { content: [{ type: 'text', text: JSON.stringify(data) }] };
16
+ }
17
+ catch (err) {
18
+ return fail(errorText(err));
19
+ }
20
+ }
21
+ function toRequest(spec, args) {
22
+ const path = spec.forward.path.includes(':id')
23
+ ? spec.forward.path.replace(':id', encodeURIComponent(requireLeadId(args)))
24
+ : spec.forward.path;
25
+ return {
26
+ path,
27
+ method: spec.forward.method,
28
+ orgId: spec.name === 'list_orgs' ? undefined : requireOrgId(args),
29
+ query: spec.forward.query ? pickQuery(args, spec.forward.query) : undefined,
30
+ body: spec.forward.body ? pick(args, spec.forward.body) : undefined,
31
+ };
32
+ }
33
+ function requireOrgId(args) {
34
+ const fromArgs = typeof args.org_id === 'string' ? args.org_id.trim() : '';
35
+ const fromEnv = process.env.WORKHIVE_ORG_ID?.trim() ?? '';
36
+ const orgId = fromArgs || fromEnv;
37
+ if (!orgId)
38
+ throw new Error(MISSING_ORG_MESSAGE);
39
+ return orgId;
40
+ }
41
+ function requireLeadId(args) {
42
+ const id = typeof args.id === 'string' ? args.id.trim() : '';
43
+ if (!id)
44
+ throw new Error('id is required');
45
+ return id;
46
+ }
47
+ function pickQuery(args, keys) {
48
+ const query = {};
49
+ for (const key of keys) {
50
+ const value = args[key];
51
+ if (value == null || value === '')
52
+ continue;
53
+ query[key] = typeof value === 'boolean' ? (value ? 'true' : 'false') : String(value);
54
+ }
55
+ return query;
56
+ }
57
+ function pick(args, keys) {
58
+ const out = {};
59
+ for (const key of keys)
60
+ if (args[key] !== undefined)
61
+ out[key] = args[key];
62
+ return out;
63
+ }
64
+ function fail(text) {
65
+ return { content: [{ type: 'text', text }], isError: true };
66
+ }
67
+ function errorText(err) {
68
+ if (err instanceof AgentRestError)
69
+ return err.message;
70
+ if (err instanceof Error)
71
+ return err.message;
72
+ return String(err);
73
+ }
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@workhive/agent",
3
+ "version": "0.2.0",
4
+ "description": "Workhive Agent Kernel MCP adapter. Five tools 1:1 with REST /api/agent/v0 over stdio.",
5
+ "type": "module",
6
+ "bin": {
7
+ "workhive-agent": "./dist/index.js"
8
+ },
9
+ "main": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
13
+ "./catalog": { "types": "./dist/catalog.d.ts", "import": "./dist/catalog.js" },
14
+ "./rules": { "types": "./dist/rules.d.ts", "import": "./dist/rules.js" },
15
+ "./tools": { "types": "./dist/tools.d.ts", "import": "./dist/tools.js" }
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "README.md"
20
+ ],
21
+ "scripts": {
22
+ "build": "tsc",
23
+ "start": "node dist/index.js"
24
+ },
25
+ "engines": {
26
+ "node": ">=18"
27
+ },
28
+ "dependencies": {
29
+ "@modelcontextprotocol/sdk": "1.30.0"
30
+ },
31
+ "devDependencies": {
32
+ "typescript": "^5.0.0"
33
+ }
34
+ }