@sellable/mcp 0.1.362 → 0.1.364

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/dist/api.d.ts CHANGED
@@ -2,6 +2,12 @@ export interface ApiResponse<T> {
2
2
  data: T;
3
3
  error?: string;
4
4
  }
5
+ export interface DownloadToFileResult {
6
+ path: string;
7
+ bytes: number;
8
+ contentType: string | null;
9
+ status: number;
10
+ }
5
11
  export declare class SellableApiError extends Error {
6
12
  status: number;
7
13
  body: string;
@@ -15,6 +21,7 @@ export declare class SellableApi {
15
21
  private request;
16
22
  get<T>(path: string): Promise<T>;
17
23
  getText(path: string): Promise<string>;
24
+ downloadToFile(requestPath: string, destinationPath: string): Promise<DownloadToFileResult>;
18
25
  post<T>(path: string, body?: object): Promise<T>;
19
26
  put<T>(path: string, body?: object): Promise<T>;
20
27
  patch<T>(path: string, body?: object): Promise<T>;
package/dist/api.js CHANGED
@@ -1,4 +1,9 @@
1
1
  import { getConfig, getConfigPath } from "./auth.js";
2
+ import { createWriteStream } from "node:fs";
3
+ import { mkdir, rename, rm, stat } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { Readable } from "node:stream";
6
+ import { pipeline } from "node:stream/promises";
2
7
  export class SellableApiError extends Error {
3
8
  status;
4
9
  body;
@@ -61,6 +66,33 @@ export class SellableApi {
61
66
  const response = await this.requestResponse("GET", path);
62
67
  return response.text();
63
68
  }
69
+ async downloadToFile(requestPath, destinationPath) {
70
+ const response = await this.requestResponse("GET", requestPath);
71
+ if (!response.body) {
72
+ throw new SellableApiError(response.status, "Response body was empty for file download");
73
+ }
74
+ await mkdir(path.dirname(destinationPath), { recursive: true });
75
+ const tempPath = `${destinationPath}.tmp-${process.pid}-${Date.now()}`;
76
+ let completed = false;
77
+ try {
78
+ const nodeStream = Readable.fromWeb(response.body);
79
+ await pipeline(nodeStream, createWriteStream(tempPath, { flags: "wx" }));
80
+ const fileStat = await stat(tempPath);
81
+ await rename(tempPath, destinationPath);
82
+ completed = true;
83
+ return {
84
+ path: destinationPath,
85
+ bytes: fileStat.size,
86
+ contentType: response.headers.get("content-type"),
87
+ status: response.status,
88
+ };
89
+ }
90
+ finally {
91
+ if (!completed) {
92
+ await rm(tempPath, { force: true }).catch(() => undefined);
93
+ }
94
+ }
95
+ }
64
96
  async post(path, body) {
65
97
  return this.request("POST", path, body);
66
98
  }
package/dist/index-dev.js CHANGED
File without changes
package/dist/index.js CHANGED
File without changes
package/dist/server.js CHANGED
@@ -48,6 +48,7 @@ import { exportTableCsv, listTables } from "./tools/tables.js";
48
48
  import { handleVerifyTableRow } from "./tools/verify-row.js";
49
49
  import { sanitizeWatchUrlsForMcpResult } from "./tools/watch-url-security.js";
50
50
  import { getCampaignWaterfall, setCampaignWaterfallOrder, } from "./tools/waterfalls.js";
51
+ import { exportWorkspaceCsv } from "./tools/workspace-export.js";
51
52
  import { addTeammate, createWorkspace, getActiveWorkspace, listWorkspaces, setActiveWorkspace, } from "./tools/workspaces.js";
52
53
  import { checkForUpdates, logUpdateNotice } from "./update-check.js";
53
54
  const server = new Server({
@@ -75,8 +76,9 @@ function markEvergreenSetupCampaignsDirty(args) {
75
76
  const campaignIds = new Set();
76
77
  const bindings = Array.isArray(args.bindings) ? args.bindings : [];
77
78
  for (const binding of bindings) {
78
- if (!binding || typeof binding !== "object" || Array.isArray(binding))
79
+ if (!binding || typeof binding !== "object" || Array.isArray(binding)) {
79
80
  continue;
81
+ }
80
82
  const campaignId = binding.campaignId;
81
83
  if (typeof campaignId === "string" && campaignId.trim()) {
82
84
  campaignIds.add(campaignId.trim());
@@ -84,8 +86,9 @@ function markEvergreenSetupCampaignsDirty(args) {
84
86
  }
85
87
  const receipts = Array.isArray(args.receipts) ? args.receipts : [];
86
88
  for (const receipt of receipts) {
87
- if (!receipt || typeof receipt !== "object" || Array.isArray(receipt))
89
+ if (!receipt || typeof receipt !== "object" || Array.isArray(receipt)) {
88
90
  continue;
91
+ }
89
92
  const campaignId = receipt.campaignId;
90
93
  if (typeof campaignId === "string" && campaignId.trim()) {
91
94
  campaignIds.add(campaignId.trim());
@@ -388,6 +391,9 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
388
391
  case "export_table_csv":
389
392
  result = await exportTableCsv(args);
390
393
  break;
394
+ case "export_workspace_csv":
395
+ result = await exportWorkspaceCsv(args);
396
+ break;
391
397
  case "search_inbox_threads":
392
398
  result = await searchInboxThreads(args);
393
399
  break;
@@ -2,13 +2,13 @@ import { getApi } from "../api.js";
2
2
  export const cellToolDefinitions = [
3
3
  {
4
4
  name: "update_cell",
5
- description: "Update a cell's value. Use for saving crafted messages (messageCellId/subjectCellId), marking examples (exampleCellId with value: true/false), or approving an explicitly selected semantic Approved cell. For route-proof or send-review approval, use the approve cell returned by get_campaign_messages_preview or select_campaign_cells, not get_rows alone.",
5
+ description: "Update a cell's value. Use for saving crafted messages (messageCellId/subjectCellId), marking examples (exampleCellId with value: true/false), or approving for send (approveCellId with value: true).",
6
6
  inputSchema: {
7
7
  type: "object",
8
8
  properties: {
9
9
  cellId: {
10
10
  type: "string",
11
- description: "Cell ID (messageCellId/subjectCellId, exampleCellId, or a semantic Approved cell from preview/selector; not a stale get_rows approveCellId)",
11
+ description: "Cell ID (messageCellId/subjectCellId, exampleCellId, or approveCellId from row)",
12
12
  },
13
13
  value: {
14
14
  oneOf: [{ type: "string" }, { type: "boolean" }, { type: "object" }],
@@ -373,7 +373,7 @@ export function getPostFindLeadsScoutRegistry() {
373
373
  codex: 'After confirm_lead_list copies source rows and the initial campaign-table execution slice exists, ask the filter-choice question immediately. Do not spawn anything before that question. After the answer, launch only Message Drafting. The filter-choice answer is the post-import user gate for this single worker; do not ask another question about starting it in step-wise or YOLO mode. The registry lookup is not a launch: after get_post_find_leads_scout_registry, immediately invoke Task/spawn_agent or the host background-agent mechanism before loading filter-leads.md, before saving rubrics, and before treating skip-filters as ready for message review. Both choices route through this kickoff; do not let filters_skipped jump straight from filter-choice to message-generation. If filters are chosen, the parent stays on Filter Rules and drafts/saves rubrics with MCP tools while Message Drafting runs in the background. If filters are skipped, move to Messages/message review only after Message Drafting has started or is ready; update_campaign(currentStep=messages) is not proof of launch. If the named Message Drafting custom agent is unavailable, spawn a generic gpt-5.5 xhigh Message Drafting background agent with the same lean campaign/table basis. When the background worker starts, persist workerDetails.messageDraftBuilder with statusSource "branch", status "branch-running", runId, startedAt, updatedAt, basisToken when known, and basis containing campaignId, selectedLeadListId, workflowTableId, filterChoice, and reviewBatchRowHash or reviewBatchRowIds; workerStatuses.messageDraftBuilder may be "running" as a simple badge only. Never put rich proof under workerStatuses and never use workerStatuses.messageDrafting. If no background-agent tool is callable, start the same full message branch inline before filter drafting or before skip-filter message review, record workerDetails.messageDraftBuilder with statusSource "parent-thread-fallback" and status "fallback-active", and require the same live context, prompt, assets, and validation gate before message review; do not wait until filters are saved and then call the registry.',
374
374
  claude: "After confirm_lead_list copies source rows and the initial campaign-table execution slice exists, ask the filter-choice question immediately. Do not invoke any Task/Agent before that question. After the answer, invoke only Message Drafting. If filters are chosen, parent drafts/saves rubrics with MCP tools while Message Drafting runs, asks filter approval, then joins Message Drafting. If filters are skipped, invoke only Message Drafting and move to Messages/message review.",
375
375
  parentThreadRule: 'Named agents are optional acceleration, but message drafting is not optional. The only normal background worker is Message Drafting. The filter-choice answer is the campaign-scoped go-ahead for this single post-import worker; do not ask another question to start it in step-wise or YOLO mode. If a named agent is unavailable, use a generic gpt-5.5 xhigh Message Drafting background agent. source work and filter work stay in the parent thread with MCP tools. If post-find-leads-message-scout is available, run it as the background Message Draft Builder after the filter-choice answer. The registry lookup is not a launch: get_post_find_leads_scout_registry only identifies the worker, and Message Drafting counts as started only after Task/spawn_agent or the host background-agent tool is invoked, or after the parent begins the same full message branch inline because no background-agent tool is callable. This launch must happen before loading filter-leads.md, save_rubrics, filter approval, or skip-filter message review; currentStep=messages is not proof of launch. If post-find-leads-message-scout is absent, do not customer-surface install status. Do not silently treat message drafting as started; the main thread must either launch the background worker or execute the same message branch from CampaignOffer state, selected source state, workflowTableId, and initial campaign-table execution slice rows. For a spawned worker, record workerDetails.messageDraftBuilder with statusSource branch / status branch-running, runId, startedAt, updatedAt, and basis containing campaignId, selectedLeadListId, workflowTableId, filterChoice, and reviewBatchRowHash or reviewBatchRowIds. workerStatuses.messageDraftBuilder is optional simple badge text only ("running", "ready", "blocked", "idle"); never put runId/statusSource/basis under workerStatuses and never use workerStatuses.messageDrafting. If no background-agent tool is callable, start that same full message branch inline before filter drafting or before skip-filter message review, record workerDetails.messageDraftBuilder with statusSource parent-thread-fallback / status fallback-active then ready, and require the same live context, prompt, assets, and validation gate before message review; do not report that as a background worker failure. If neither branch nor inline fallback can run, return blocked/retry-needed; do not wait until filters are saved and then call the registry. The Message Drafting handoff must be lean. Do not paste copied row counts, brief hashes, review-batch hashes, full reviewBatchRowIds, broad row data, or local debug artifacts into the spawn prompt. Local markdown/json files are not normal-path inputs. The filter-choice question is the first post-import user gate; do not load post-lead registries or filter references before it. Message drafting starts after the filter-choice answer, must load get_subskill_prompt({ subskillName: "generate-messages" }), and must load every required message asset named by generate-messages Mode 0 through get_subskill_asset before drafting. Reference Asset Loading means loading the required pre-draft reference pack before drafting; return blocked/retry-needed if required assets cannot be loaded; load ai-tells.md because it is never optional. The branch or parent-thread fallback loads the full generate-messages prompt and every referenced asset through get_subskill_asset. After generating/revising the candidate and before returning ready, must load get_subskill_prompt({ subskillName: "create-campaign-v2-validation" }) as the final internal validation gate, must read live campaign table state through scoped MCP/product tools, and must reject mismatched selectedLeadListId/workflowTableId/campaign/workspace input. Do not block when filters were chosen but leadScoringRubrics are not yet visible in the branch read; the parent owns save_rubrics and filter approval in parallel, so Message Drafting should return status ready with basisStatus usable_initial when campaign/list/table identity and the non-empty execution slice match. Do not use any alternate, local-artifact, or examples-only message prompt. User copy feedback, message QA, or rewrite requests before approve-message must be routed back to Message Drafting with the current recommendation, lean campaign/table basis, and latest user text; the parent must not rewrite or QA the template from memory and must not call update_campaign_brief before approve-message. The worker validates internally and returns only templateRecommendation, tokenFillRules, renderedGoodSample, status, approveOrReviseRecommendation, validationStatus, outputAt, outputHash, and blocked/retry detail. Do not render renderedFallbackSample, risk notes, or a qaReceipt on the normal happy path. On the filter path, save_rubrics keeps the browser on Filter Rules after save_rubrics so the user can approve the saved criteria; after saved-filter approval, move to Filter Leads with currentStep=apply-icp-rubric whether Message Drafting is ready or still running. Wait there for message approval. Enrichment, filtering, Generate Message cells, sender setup, sequence attach, and launch wait for template approval on the Use Template path. On the skip path, move to Messages/message review after Message Drafting has started or is ready and wait for message approval before enrichment or Settings. Do not render message review from checklist or shortcut instructions; message review requires a messageDraftRecommendation whose basis proves the generate-messages prompt, required message assets, and validation gate ran for the current campaign/table execution slice. Do not automatically rerun Message Drafting after filters/enrichment finish; show the initial draft by default and offer an enriched rewrite only with explicit user opt-in. Handoff and recommendation output are Markdown with labeled fields, not raw JSON.',
376
- prepareMessagesRule: `Default create-campaign stays on the existing reviewBatchLimit:15 first campaign-table execution slice. For plain post-mint fill/load/refill requests, load get_subskill_prompt({ subskillName: "refill-sends-workflow" }), then call resolve_campaign_fill_route({ intent:"plain" }) and get_campaign_refill_state before any mutation. Route outcomes are route:"evergreen_horizon", route:"active_campaigns", and route:"ask_create"; stay in the same campaignOfferId/campaignId context after minting. Plain fill is not an alias for fill_campaign_horizon or campaign creation. fill_campaign_horizon is evergreen-only and is not the generic regular-campaign fill path. Campaign creation is allowed only after route:"ask_create" and explicit user selection; it is never the default response to plain fill. Treat "fill up/load sends" as capacity-fill preparation: calculate the bounded target from sender capacity when needed, then use the refill workflow to decide same-campaign source replenishment, enrichment/prep, approval/ready state, scheduler reread, and sender-health blockers. Do not create warm-post-engager side campaigns. For already-running regular campaigns that need Signal Discovery source replenishment, use the guarded currentStep clear with clearCurrentStepIfMatches:"running", campaign-scoped provider prompt/search/select, and import_leads with the existing sourceLeadListId when a newly approved selected-post scrape would otherwise return reusedExistingSourceList. After confirm_lead_list copies rows into an existing table, avoid fixed maxRowsToCheck:100; inspect reviewBatch/table selectors or use adaptive/wider bounded prep so appended rows are included. Do not interpret checkedRows as enriched rows; it is only the table cursor. Prepared, approved, and ready_to_schedule rows are intermediate states; never call them scheduled unless a re-read proves scheduler-owned scheduled cells with non-null scheduledFor. Before source import, prep, or approval, require exact visible approval and a fresh get_campaign_refill_state reread; stop if freshness.stateHash or exact ids changed. For "approve X messages", use approvalMode:approve only when explicitly requested, but still do not launch. For "schedule X sends" or "fill sender sends", approve only when explicitly requested, then re-read campaign/table scheduled counts; if scheduler-owned scheduledFor cells are not present, report prepared/approved/ready - awaiting scheduler instead of success. Do not call start_campaign as part of fill/schedule horizon. Do not call start_campaign as part of refill sends. Launch/start is a separate explicit human action after the operator intentionally wants sends to go out, and it must still verify that the bounded cohort is the only approved cohort and must not broad approve-all. campaignId is CampaignOffer.id. If the user asks to stop preparation, the target is wrong, or status shows the wrong campaign/table, use cancel_campaign_message_preparation only for the exact active job. Low-level selectors are diagnostics and recovery only for this lane. start_campaign remains forbidden until explicit launch/start approval outside refill sends.`,
376
+ prepareMessagesRule: `Default create-campaign stays on the existing reviewBatchLimit:15 first campaign-table execution slice. For plain post-mint fill/load/refill requests, load get_subskill_prompt({ subskillName: "refill-sends-workflow" }), then call resolve_campaign_fill_route({ intent:"plain" }) and get_campaign_refill_state before any mutation. Route outcomes are route:"evergreen_horizon", route:"active_campaigns", and route:"ask_create"; stay in the same campaignOfferId/campaignId context after minting. Plain fill is not an alias for fill_campaign_horizon or campaign creation. fill_campaign_horizon is evergreen-only and is not the generic regular-campaign fill path. Campaign creation is allowed only after route:"ask_create" and explicit user selection; it is never the default response to plain fill. Treat "fill up/load sends" as capacity-fill preparation: calculate the bounded target from sender capacity when needed, then use the refill workflow to decide same-campaign source replenishment, enrichment/prep, approval/ready state, scheduler reread, and sender-health blockers. Do not create warm-post-engager side campaigns. Do not interpret checkedRows as enriched rows; it is only the table cursor. Prepared, approved, and ready_to_schedule rows are intermediate states; never call them scheduled unless a re-read proves scheduler-owned scheduled cells with non-null scheduledFor. Before source import, prep, or approval, require exact visible approval and a fresh get_campaign_refill_state reread; stop if freshness.stateHash or exact ids changed. For "approve X messages", use approvalMode:approve only when explicitly requested, but still do not launch. For "schedule X sends" or "fill sender sends", approve only when explicitly requested, then re-read campaign/table scheduled counts; if scheduler-owned scheduledFor cells are not present, report prepared/approved/ready - awaiting scheduler instead of success. Do not call start_campaign as part of fill/schedule horizon. Do not call start_campaign as part of refill sends. Launch/start is a separate explicit human action after the operator intentionally wants sends to go out, and it must still verify that the bounded cohort is the only approved cohort and must not broad approve-all. campaignId is CampaignOffer.id. If the user asks to stop preparation, the target is wrong, or status shows the wrong campaign/table, use cancel_campaign_message_preparation only for the exact active job. Low-level selectors are diagnostics and recovery only for this lane. start_campaign remains forbidden until explicit launch/start approval outside refill sends.`,
377
377
  },
378
378
  };
379
379
  }
@@ -42,6 +42,7 @@ import { setupEvergreenCampaignsToolDefinitions } from "./setup-evergreen-campai
42
42
  import { tableToolDefinitions } from "./tables.js";
43
43
  import { verifyRowToolDefinitions } from "./verify-row.js";
44
44
  import { waterfallToolDefinitions } from "./waterfalls.js";
45
+ import { workspaceExportToolDefinitions } from "./workspace-export.js";
45
46
  import { workspaceToolDefinitions } from "./workspaces.js";
46
47
  export const allTools = [
47
48
  ...campaignToolDefinitions,
@@ -83,6 +84,7 @@ export const allTools = [
83
84
  ...engageMemoryToolDefinitions,
84
85
  ...sequencerToolDefinitions,
85
86
  ...tableToolDefinitions,
87
+ ...workspaceExportToolDefinitions,
86
88
  ...columnSchemaToolDefinitions,
87
89
  ...blueprintCommitToolDefinitions,
88
90
  ...columnUpdateToolDefinitions,
@@ -50,7 +50,7 @@ export const rowToolDefinitions = [
50
50
  },
51
51
  {
52
52
  name: "get_rows",
53
- description: "Get row details for crafting. Returns: name, company, title, linkedinUrl, currentMessage, currentSubject, messageCellId, subjectCellId, approveCellId, exampleCellId, isExample, carryData (extra CSV columns like 'Jobs Hiring For'), enrichment (summary, experience, education). Use after selecting a lead. Do not treat approveCellId from get_rows as the product-visible approval source of truth; on campaign tables it can differ from the send-review Approved column. For route-proof or send-review approval, use get_campaign_messages_preview or select_campaign_cells to select the semantic Approved cell.",
53
+ description: "Get row details for crafting. Returns: name, company, title, linkedinUrl, currentMessage, currentSubject, messageCellId, subjectCellId, approveCellId, exampleCellId, isExample, carryData (extra CSV columns like 'Jobs Hiring For'), enrichment (summary, experience, education). Use after selecting a lead.",
54
54
  inputSchema: {
55
55
  type: "object",
56
56
  properties: {
@@ -13,7 +13,7 @@ type SetupEvergreenCampaignsInput = {
13
13
  }>;
14
14
  planRevision?: string;
15
15
  selectedActionIds?: string[];
16
- receipts?: unknown[];
16
+ receipts?: Array<Record<string, unknown>>;
17
17
  };
18
18
  export declare const setupEvergreenCampaignsToolDefinitions: {
19
19
  name: string;
@@ -0,0 +1,82 @@
1
+ export type WorkspaceExportDataset = "people" | "events";
2
+ export interface ExportWorkspaceCsvInput {
3
+ exportType?: "outreach";
4
+ datasets?: WorkspaceExportDataset[];
5
+ outputDir?: string;
6
+ fromSentAt?: string;
7
+ toSentAt?: string;
8
+ campaignIds?: string[];
9
+ tableIds?: string[];
10
+ }
11
+ export declare const workspaceExportToolDefinitions: {
12
+ name: string;
13
+ description: string;
14
+ inputSchema: {
15
+ type: string;
16
+ properties: {
17
+ exportType: {
18
+ type: string;
19
+ enum: string[];
20
+ description: string;
21
+ };
22
+ datasets: {
23
+ type: string;
24
+ items: {
25
+ type: string;
26
+ enum: string[];
27
+ };
28
+ description: string;
29
+ };
30
+ outputDir: {
31
+ type: string;
32
+ description: string;
33
+ };
34
+ fromSentAt: {
35
+ type: string;
36
+ description: string;
37
+ };
38
+ toSentAt: {
39
+ type: string;
40
+ description: string;
41
+ };
42
+ campaignIds: {
43
+ type: string;
44
+ items: {
45
+ type: string;
46
+ };
47
+ description: string;
48
+ };
49
+ tableIds: {
50
+ type: string;
51
+ items: {
52
+ type: string;
53
+ };
54
+ description: string;
55
+ };
56
+ };
57
+ required: never[];
58
+ additionalProperties: boolean;
59
+ };
60
+ }[];
61
+ export declare function exportWorkspaceCsv(input?: ExportWorkspaceCsvInput): Promise<{
62
+ status: string;
63
+ outputDir: string;
64
+ manifestPath: string;
65
+ datasets: {
66
+ dataset: WorkspaceExportDataset;
67
+ path: string;
68
+ rows: number;
69
+ bytes: number;
70
+ status: "complete" | "failed";
71
+ }[];
72
+ exportCutoff: string;
73
+ workspace: {
74
+ id?: string;
75
+ name?: string | null;
76
+ };
77
+ skipped: string[];
78
+ failures: {
79
+ dataset: WorkspaceExportDataset;
80
+ error: string;
81
+ }[];
82
+ }>;
@@ -0,0 +1,328 @@
1
+ import { parse } from "csv-parse";
2
+ import { createReadStream } from "node:fs";
3
+ import { lstat, mkdir, readFile, rename, rm, writeFile, } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { getApi } from "../api.js";
7
+ import { getConfig } from "../auth.js";
8
+ const MAX_FILTER_IDS = 100;
9
+ const MAX_QUERY_LENGTH = 8000;
10
+ export const workspaceExportToolDefinitions = [
11
+ {
12
+ name: "export_workspace_csv",
13
+ description: "Export active-workspace outreach CSVs to local files on the MCP host. " +
14
+ "Phase 70 supports workflow-table-backed reached-out people and event-level outreach only. " +
15
+ "Requires a valid Sellable API key plus active workspace; run list_workspaces and set_active_workspace first if needed. " +
16
+ "The manifest includes file paths, counts, filters, package/runtime metadata, and skipped/deferred scope notes. " +
17
+ "CSV files may contain prospect and outreach metadata, so store them appropriately.",
18
+ inputSchema: {
19
+ type: "object",
20
+ properties: {
21
+ exportType: {
22
+ type: "string",
23
+ enum: ["outreach"],
24
+ description: "Export family. Phase 70 supports outreach only.",
25
+ },
26
+ datasets: {
27
+ type: "array",
28
+ items: { type: "string", enum: ["people", "events"] },
29
+ description: "Datasets to export. Defaults to both people and events.",
30
+ },
31
+ outputDir: {
32
+ type: "string",
33
+ description: "Optional base directory. A unique run subdirectory is created inside it.",
34
+ },
35
+ fromSentAt: {
36
+ type: "string",
37
+ description: "Optional ISO lower bound for outreach sentAt.",
38
+ },
39
+ toSentAt: {
40
+ type: "string",
41
+ description: "Optional ISO upper bound for outreach sentAt.",
42
+ },
43
+ campaignIds: {
44
+ type: "array",
45
+ items: { type: "string" },
46
+ description: "Optional campaign ids to include, max 100.",
47
+ },
48
+ tableIds: {
49
+ type: "array",
50
+ items: { type: "string" },
51
+ description: "Optional workflow table ids to include, max 100.",
52
+ },
53
+ },
54
+ required: [],
55
+ additionalProperties: false,
56
+ },
57
+ },
58
+ ];
59
+ function assertIsoDate(value, field) {
60
+ if (value === undefined || value === null || value === "")
61
+ return undefined;
62
+ if (typeof value !== "string")
63
+ throw new Error(`${field} must be a string`);
64
+ const date = new Date(value);
65
+ if (!Number.isFinite(date.getTime())) {
66
+ throw new Error(`${field} must be a valid ISO date`);
67
+ }
68
+ return date.toISOString();
69
+ }
70
+ function assertIdList(value, field) {
71
+ if (value === undefined || value === null)
72
+ return [];
73
+ if (!Array.isArray(value))
74
+ throw new Error(`${field} must be an array`);
75
+ if (value.length > MAX_FILTER_IDS) {
76
+ throw new Error(`${field} supports at most ${MAX_FILTER_IDS} ids`);
77
+ }
78
+ return value.map((id) => {
79
+ if (typeof id !== "string" || !/^[A-Za-z0-9_.:-]+$/.test(id)) {
80
+ throw new Error(`${field} contains an invalid id`);
81
+ }
82
+ return id;
83
+ });
84
+ }
85
+ function normalizeDatasets(value) {
86
+ if (value === undefined || value === null)
87
+ return ["people", "events"];
88
+ if (!Array.isArray(value))
89
+ throw new Error("datasets must be an array");
90
+ if (value.length === 0)
91
+ throw new Error("datasets cannot be empty");
92
+ const unique = Array.from(new Set(value));
93
+ return unique.map((dataset) => {
94
+ if (dataset !== "people" && dataset !== "events") {
95
+ throw new Error("datasets may only contain people or events");
96
+ }
97
+ return dataset;
98
+ });
99
+ }
100
+ function validateInput(input) {
101
+ if (input.exportType && input.exportType !== "outreach") {
102
+ throw new Error("exportType must be outreach");
103
+ }
104
+ const fromSentAt = assertIsoDate(input.fromSentAt, "fromSentAt");
105
+ const toSentAt = assertIsoDate(input.toSentAt, "toSentAt");
106
+ if (fromSentAt && toSentAt && new Date(fromSentAt) > new Date(toSentAt)) {
107
+ throw new Error("fromSentAt must be before toSentAt");
108
+ }
109
+ return {
110
+ datasets: normalizeDatasets(input.datasets),
111
+ outputDir: input.outputDir,
112
+ fromSentAt,
113
+ toSentAt,
114
+ campaignIds: assertIdList(input.campaignIds, "campaignIds"),
115
+ tableIds: assertIdList(input.tableIds, "tableIds"),
116
+ };
117
+ }
118
+ async function packageVersion() {
119
+ const entryDir = process.argv[1]
120
+ ? path.dirname(path.resolve(process.argv[1]))
121
+ : process.cwd();
122
+ const candidates = [
123
+ path.resolve(process.cwd(), "mcp/sellable/package.json"),
124
+ path.resolve(entryDir, "../package.json"),
125
+ path.resolve(entryDir, "../../package.json"),
126
+ ];
127
+ for (const candidate of candidates) {
128
+ try {
129
+ const raw = await readFile(candidate, "utf8");
130
+ const parsed = JSON.parse(raw);
131
+ if (typeof parsed.version === "string")
132
+ return parsed.version;
133
+ }
134
+ catch {
135
+ // Try the next runtime/package layout.
136
+ }
137
+ }
138
+ return null;
139
+ }
140
+ async function ensureSafeBaseDir(outputDir) {
141
+ const baseDir = path.resolve(outputDir || path.join(tmpdir(), "sellable-mcp-exports"));
142
+ await mkdir(baseDir, { recursive: true });
143
+ const baseStat = await lstat(baseDir);
144
+ if (baseStat.isSymbolicLink()) {
145
+ throw new Error("outputDir must not be a symlink");
146
+ }
147
+ if (!baseStat.isDirectory()) {
148
+ throw new Error("outputDir must be a directory");
149
+ }
150
+ return baseDir;
151
+ }
152
+ async function createRunDir(outputDir) {
153
+ const baseDir = await ensureSafeBaseDir(outputDir);
154
+ for (let attempt = 0; attempt < 10; attempt++) {
155
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
156
+ const runDir = path.join(baseDir, `workspace-outreach-${stamp}-${process.pid}-${attempt}`);
157
+ try {
158
+ await mkdir(runDir, { recursive: false });
159
+ return runDir;
160
+ }
161
+ catch (error) {
162
+ if (error.code !== "EEXIST")
163
+ throw error;
164
+ }
165
+ }
166
+ throw new Error("Failed to create unique export directory");
167
+ }
168
+ function buildQuery(params) {
169
+ const searchParams = new URLSearchParams();
170
+ for (const [key, value] of Object.entries(params)) {
171
+ if (Array.isArray(value)) {
172
+ if (value.length > 0)
173
+ searchParams.set(key, value.join(","));
174
+ }
175
+ else if (value) {
176
+ searchParams.set(key, value);
177
+ }
178
+ }
179
+ const query = searchParams.toString();
180
+ if (query.length > MAX_QUERY_LENGTH) {
181
+ throw new Error("Export query string is too long");
182
+ }
183
+ return query ? `?${query}` : "";
184
+ }
185
+ async function countCsvRows(filePath) {
186
+ const parser = createReadStream(filePath).pipe(parse({ bom: true, relax_column_count: true }));
187
+ let records = 0;
188
+ for await (const _record of parser) {
189
+ records += 1;
190
+ }
191
+ return Math.max(0, records - 1);
192
+ }
193
+ function redactManifest(value) {
194
+ if (Array.isArray(value))
195
+ return value.map(redactManifest);
196
+ if (!value || typeof value !== "object")
197
+ return value;
198
+ const entries = Object.entries(value).map(([key, entry]) => {
199
+ if (/token|secret|authorization|api[_-]?key/i.test(key)) {
200
+ return [key, "[redacted]"];
201
+ }
202
+ return [key, redactManifest(entry)];
203
+ });
204
+ return Object.fromEntries(entries);
205
+ }
206
+ async function writeJsonAtomic(filePath, value) {
207
+ const tempPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
208
+ await writeFile(tempPath, `${JSON.stringify(value, null, 2)}\n`, {
209
+ encoding: "utf8",
210
+ flag: "wx",
211
+ });
212
+ await rename(tempPath, filePath);
213
+ }
214
+ export async function exportWorkspaceCsv(input = {}) {
215
+ const config = getConfig();
216
+ const workspaceId = config.activeWorkspaceId || config.workspaceId || null;
217
+ if (!workspaceId) {
218
+ throw new Error("No active workspace selected. Run list_workspaces then set_active_workspace before export_workspace_csv.");
219
+ }
220
+ const validated = validateInput(input);
221
+ const startedAt = new Date().toISOString();
222
+ const runDir = await createRunDir(validated.outputDir);
223
+ const api = getApi();
224
+ const metadataQuery = buildQuery({
225
+ fromSentAt: validated.fromSentAt,
226
+ toSentAt: validated.toSentAt,
227
+ campaignIds: validated.campaignIds,
228
+ tableIds: validated.tableIds,
229
+ });
230
+ const metadataEndpoint = `/api/v3/mcp/workspace-export/outreach/metadata${metadataQuery}`;
231
+ const backendMetadata = await api.get(metadataEndpoint);
232
+ const exportCutoff = backendMetadata.exportCutoff;
233
+ if (!exportCutoff) {
234
+ throw new Error("Export metadata did not include exportCutoff");
235
+ }
236
+ const files = [];
237
+ const failures = [];
238
+ for (const dataset of validated.datasets) {
239
+ const query = buildQuery({
240
+ dataset,
241
+ exportCutoff,
242
+ fromSentAt: validated.fromSentAt,
243
+ toSentAt: validated.toSentAt,
244
+ campaignIds: validated.campaignIds,
245
+ tableIds: validated.tableIds,
246
+ });
247
+ const endpoint = `/api/v3/mcp/workspace-export/outreach${query}`;
248
+ const filePath = path.join(runDir, `outreach-${dataset}.csv`);
249
+ try {
250
+ const download = await api.downloadToFile(endpoint, filePath);
251
+ files.push({
252
+ dataset,
253
+ path: download.path,
254
+ rows: await countCsvRows(download.path),
255
+ bytes: download.bytes,
256
+ endpoint,
257
+ contentType: download.contentType,
258
+ status: "complete",
259
+ });
260
+ }
261
+ catch (error) {
262
+ const message = error instanceof Error ? error.message : "Unknown error";
263
+ failures.push({ dataset, error: message });
264
+ files.push({
265
+ dataset,
266
+ path: filePath,
267
+ rows: 0,
268
+ bytes: 0,
269
+ endpoint,
270
+ contentType: null,
271
+ status: "failed",
272
+ error: message,
273
+ });
274
+ await rm(filePath, { force: true }).catch(() => undefined);
275
+ }
276
+ }
277
+ const manifest = redactManifest({
278
+ status: failures.length > 0 ? "partial" : "success",
279
+ tool: "export_workspace_csv",
280
+ exportType: "outreach",
281
+ startedAt,
282
+ completedAt: new Date().toISOString(),
283
+ package: {
284
+ name: "@sellable/mcp",
285
+ version: await packageVersion(),
286
+ },
287
+ config: {
288
+ apiUrl: config.apiUrl,
289
+ activeWorkspaceId: workspaceId,
290
+ activeWorkspaceName: config.activeWorkspaceName || config.workspaceName,
291
+ },
292
+ backend: {
293
+ metadataEndpoint,
294
+ metadata: backendMetadata,
295
+ },
296
+ filters: {
297
+ fromSentAt: validated.fromSentAt ?? null,
298
+ toSentAt: validated.toSentAt ?? null,
299
+ campaignIds: validated.campaignIds,
300
+ tableIds: validated.tableIds,
301
+ exportCutoff,
302
+ },
303
+ outputDir: runDir,
304
+ files,
305
+ failures,
306
+ });
307
+ const manifestPath = path.join(runDir, "manifest.json");
308
+ await writeJsonAtomic(manifestPath, manifest);
309
+ return {
310
+ status: failures.length > 0 ? "partial" : "success",
311
+ outputDir: runDir,
312
+ manifestPath,
313
+ datasets: files.map((file) => ({
314
+ dataset: file.dataset,
315
+ path: file.path,
316
+ rows: file.rows,
317
+ bytes: file.bytes,
318
+ status: file.status,
319
+ })),
320
+ exportCutoff,
321
+ workspace: backendMetadata.workspace ?? {
322
+ id: workspaceId,
323
+ name: config.activeWorkspaceName || config.workspaceName || null,
324
+ },
325
+ skipped: backendMetadata.skipped ?? [],
326
+ failures,
327
+ };
328
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sellable/mcp",
3
- "version": "0.1.362",
3
+ "version": "0.1.364",
4
4
  "type": "module",
5
5
  "description": "Sellable MCP server for Claude Code and Codex campaign workflows",
6
6
  "main": "dist/index.js",
@@ -142,14 +142,6 @@ Treat active fills as capacity-fill preparation: calculate the bounded target
142
142
  from sender capacity when needed, then use the refill workflow to decide source
143
143
  replenishment, enrichment/prep, approval policy, and scheduler proof. Mutation
144
144
  requires exact visible approval and a fresh `get_campaign_refill_state` reread.
145
- For already-running regular campaigns that need Signal Discovery source
146
- replenishment, the refill workflow owns the guarded recovery: clear
147
- `currentStep` only with `clearCurrentStepIfMatches:"running"`, load the
148
- campaign-scoped provider prompt, run campaign-scoped `search_signals`, select
149
- posts with a capacity-target scrape plan, import into the same source path, and
150
- restore Running through `confirm_lead_list`. If the copied rows append beyond
151
- the first table page, inspect `reviewBatch` with table-schema/selector tools and
152
- use adaptive or wider bounded message prep; do not rely on a fixed `maxRowsToCheck:100` pass after source copy.
153
145
  If the user says "prepare/generate X messages", use message-prep primitives with
154
146
  `targetPreparedMessages:X` and default `approvalMode:"mark_ready"`. If the user
155
147
  says "approve X messages", use `approvalMode:"approve"` only for the bounded
@@ -63,15 +63,6 @@ currentStep: "sequence" })` to attach the sender via the v3 senders route and
63
63
  and Paid InMail Campaign is only an explicit paid-InMail opt-in because it
64
64
  can spend InMail credits. If that response does not persist `currentStep:
65
65
  "send"`, call `update_campaign({ campaignId, currentStep: "send" })`.
66
- Then reread `get_campaign({ campaignId })` and `list_tables()` and verify the
67
- current `workflowTableId` has `hasSequence:true`. A campaign-level
68
- `SEQUENCE_EXISTS` response is not enough when `confirm_lead_list` or another
69
- copy step has moved the campaign to a new current campaign table while an old
70
- stale shell table still owns the sequence columns. In that stale-shell case,
71
- either repair only the current workflowTableId with `attach_sequence` using
72
- the same non-paid product template the recommended selector would have chosen,
73
- or stop and report the stale-shell sequence blocker if replacement was not
74
- explicitly approved. Never choose a paid-InMail template for this repair.
75
66
  9. Surface the `handoff.orientation` string from `auto-execute.yaml` and
76
67
  summarize the visible Settings/Sequence/Send state without repeating the
77
68
  watch URL.
@@ -150,11 +141,7 @@ order, atomically:
150
141
  2. **Validate sender + sequence state.** If no sender is attached, refuse start
151
142
  and return the Settings link. If no sequence is attached but a sender is
152
143
  attached, call `attach_recommended_sequence({ campaignId, currentStep:
153
- "send" })` before approving messages, then rerun the precondition check against
154
- the current workflowTableId rather than an older shell table. If
155
- `SEQUENCE_EXISTS` only proves an old shell while the current table lacks
156
- `hasSequence:true`, stop or perform the explicitly approved stale-shell
157
- current-table repair before any launch.
144
+ "send" })` before approving messages.
158
145
  3. **Approve generated messages** through the bounded or broad path:
159
146
  - If the user asked for an exact send count, such as "schedule 250 sends",
160
147
  verify the preparation job approved only the bounded prepared cohort for