Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
feat(mcp): add add_jobs_batch and save_match_results_batch tools
Khuram Niaz1bb227036e90
diff --git a/__tests__/mcpBatch.spec.ts b/__tests__/mcpBatch.spec.tsnew file mode 100644index 0000000..bbfd4dc--- /dev/null+++ b/__tests__/mcpBatch.spec.ts@@ -0,0 +1,141 @@+import { handleAddJobsBatch } from "@/lib/mcp/tools/addJobsBatch";+import { handleSaveMatchResultsBatch } from "@/lib/mcp/tools/saveMatchResultsBatch";+import { handleAddJob } from "@/lib/mcp/tools/addJob";+import { handleSaveMatchResult } from "@/lib/mcp/tools/saveMatchResult";++vi.mock("@/lib/mcp/tools/addJob", () => ({ handleAddJob: vi.fn() }));+vi.mock("@/lib/mcp/tools/saveMatchResult", () => ({+ handleSaveMatchResult: vi.fn(),+}));++const job = (company: string) => ({+ company,+ jobTitle: "Engineer",+ jobDescription: "x".repeat(60),+});++describe("handleAddJobsBatch", () => {+ beforeEach(() => vi.clearAllMocks());++ it("processes every item in order and labels each result", async () => {+ (handleAddJob as any)+ .mockResolvedValueOnce({ content: [{ type: "text", text: "first ok" }] })+ .mockResolvedValueOnce({ content: [{ type: "text", text: "second ok" }] });++ const result = await handleAddJobsBatch(+ { jobs: [job("Acme"), job("Globex")] } as any,+ "user-1",+ "my-token",+ );+ const text = result.content[0].text;++ expect(handleAddJob).toHaveBeenCalledTimes(2);+ expect(text).toContain("[1/2] Acme — Engineer: first ok");+ expect(text).toContain("[2/2] Globex — Engineer: second ok");+ expect(text.indexOf("[1/2]")).toBeLessThan(text.indexOf("[2/2]"));+ });++ it("runs items sequentially, not concurrently", async () => {+ const order: string[] = [];+ (handleAddJob as any).mockImplementation(async (input: any) => {+ order.push(`start-${input.company}`);+ await new Promise((r) => setTimeout(r, 0));+ order.push(`end-${input.company}`);+ return { content: [{ type: "text", text: "ok" }] };+ });++ await handleAddJobsBatch(+ { jobs: [job("Acme"), job("Globex")] } as any,+ "user-1",+ "my-token",+ );++ expect(order).toEqual([+ "start-Acme",+ "end-Acme",+ "start-Globex",+ "end-Globex",+ ]);+ });++ it("continues after a failing item and reports the error inline", async () => {+ (handleAddJob as any)+ .mockRejectedValueOnce(new Error("boom"))+ .mockResolvedValueOnce({ content: [{ type: "text", text: "second ok" }] });++ const result = await handleAddJobsBatch(+ { jobs: [job("Acme"), job("Globex")] } as any,+ "user-1",+ "my-token",+ );+ const text = result.content[0].text;++ expect(text).toContain("[1/2] Acme — Engineer: Error: boom");+ expect(text).toContain("[2/2] Globex — Engineer: second ok");+ });++ it("stops the run when an item hits the rate limit", async () => {+ (handleAddJob as any)+ .mockResolvedValueOnce({ content: [{ type: "text", text: "first ok" }] })+ .mockResolvedValueOnce({+ content: [{ type: "text", text: "Rate limit exceeded. Try again in 30s." }],+ });++ const result = await handleAddJobsBatch(+ { jobs: [job("A"), job("B"), job("C")] } as any,+ "user-1",+ "my-token",+ );+ const text = result.content[0].text;++ expect(handleAddJob).toHaveBeenCalledTimes(2);+ expect(text).toContain("Rate limit exceeded");+ expect(text).toContain("1 item(s) not attempted");+ });+});++describe("handleSaveMatchResultsBatch", () => {+ beforeEach(() => vi.clearAllMocks());++ it("processes every result and labels each by jobId", async () => {+ (handleSaveMatchResult as any)+ .mockResolvedValueOnce({ content: [{ type: "text", text: "saved 1" }] })+ .mockResolvedValueOnce({ content: [{ type: "text", text: "saved 2" }] });++ const result = await handleSaveMatchResultsBatch(+ {+ results: [+ { jobId: "job-1", matchText: "SCORES: match=80 recommendation=good\n\nbody" },+ { jobId: "job-2", matchText: "SCORES: match=50 recommendation=weak\n\nbody" },+ ],+ } as any,+ "user-1",+ "my-token",+ );+ const text = result.content[0].text;++ expect(handleSaveMatchResult).toHaveBeenCalledTimes(2);+ expect(text).toContain("[1/2] job-1: saved 1");+ expect(text).toContain("[2/2] job-2: saved 2");+ });++ it("continues after a failing item", async () => {+ (handleSaveMatchResult as any)+ .mockRejectedValueOnce(new Error("nope"))+ .mockResolvedValueOnce({ content: [{ type: "text", text: "saved 2" }] });++ const result = await handleSaveMatchResultsBatch(+ {+ results: [+ { jobId: "job-1", matchText: "a" },+ { jobId: "job-2", matchText: "b" },+ ],+ } as any,+ "user-1",+ "my-token",+ );++ expect(result.content[0].text).toContain("[1/2] job-1: Error: nope");+ expect(result.content[0].text).toContain("[2/2] job-2: saved 2");+ });+});diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.tsindex af9aff0..04f58a4 100644--- a/src/app/api/mcp/route.ts+++ b/src/app/api/mcp/route.ts@@ -16,6 +16,10 @@ import {McpFindJobSchema,McpUpdateJobInputShape,McpUpdateJobSchema,+ McpAddJobsBatchInputShape,+ McpAddJobsBatchSchema,+ McpSaveMatchResultsBatchInputShape,+ McpSaveMatchResultsBatchSchema,} from "@/models/mcp.schema";import { handleAddJob } from "@/lib/mcp/tools/addJob";import { handleAddQuestion } from "@/lib/mcp/tools/addQuestion";@@ -24,6 +28,8 @@ import { handleReviewResume } from "@/lib/mcp/tools/reviewResume";import { handleSaveResumeReview } from "@/lib/mcp/tools/saveResumeReview";import { handleFindJob } from "@/lib/mcp/tools/findJob";import { handleUpdateJob } from "@/lib/mcp/tools/updateJob";+import { handleAddJobsBatch } from "@/lib/mcp/tools/addJobsBatch";+import { handleSaveMatchResultsBatch } from "@/lib/mcp/tools/saveMatchResultsBatch";function isMcpEnabled(): boolean {const env = process.env.MCP_ENABLED;@@ -180,6 +186,52 @@ async function handler(req: Request): Promise<Response> {},);+ server.tool(+ "add_jobs_batch",+ "Add several jobs in one call. Same per-item behaviour as add_job (including upsert and the match directive); returns one labelled result per item. Use this for scheduled runs instead of N sequential add_job calls.",+ McpAddJobsBatchInputShape,+ async (rawInput) => {+ if (!auth.scopes.includes("jobs:write")) {+ return {+ content: [+ { type: "text" as const, text: "Insufficient scope. Required: jobs:write" },+ ],+ };+ }+ const parsed = McpAddJobsBatchSchema.safeParse(rawInput);+ if (!parsed.success) {+ const issues = parsed.error.issues.map((i) => i.message).join("; ");+ return {+ content: [{ type: "text" as const, text: `Validation error: ${issues}` }],+ };+ }+ return handleAddJobsBatch(parsed.data, userId, tokenName);+ },+ );++ server.tool(+ "save_match_results_batch",+ "Persist several job-fit match analyses in one call. Same per-item behaviour as save_match_result; returns one labelled result per item.",+ McpSaveMatchResultsBatchInputShape,+ async (rawInput) => {+ if (!auth.scopes.includes("jobs:write")) {+ return {+ content: [+ { type: "text" as const, text: "Insufficient scope. Required: jobs:write" },+ ],+ };+ }+ const parsed = McpSaveMatchResultsBatchSchema.safeParse(rawInput);+ if (!parsed.success) {+ const issues = parsed.error.issues.map((i) => i.message).join("; ");+ return {+ content: [{ type: "text" as const, text: `Validation error: ${issues}` }],+ };+ }+ return handleSaveMatchResultsBatch(parsed.data, userId, tokenName);+ },+ );+// No scope gate, intentionally — unlike the tools above, review_resume and// save_resume_review have no `resume:write` check. Tokens created before// this feature shipped don't have that scope and must keep working (seediff --git a/src/lib/constants.ts b/src/lib/constants.tsindex 62f154a..b993485 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -113,6 +113,9 @@ export const APP_CONSTANTS = {DESCRIPTION_FULL_MIN_WORDS: 150,MCP_MATCH_PROVIDER_MARKER: "mcp",MCP_REVIEW_MIN_RESUME_LENGTH: 400,+ // Batch items are processed sequentially and each consumes one unit of the+ // shared MCP rate-limit budget, so this caps a single call at a sixth of it.+ MCP_BATCH_MAX_ITEMS: 10,// File uploadsUPLOADS_DIR: process.env.NODE_ENV !== "production" ? "data" : "/data",diff --git a/src/lib/mcp/tools/addJobsBatch.ts b/src/lib/mcp/tools/addJobsBatch.tsnew file mode 100644index 0000000..8df22cc--- /dev/null+++ b/src/lib/mcp/tools/addJobsBatch.ts@@ -0,0 +1,40 @@+import { z } from "zod";+import { McpAddJobSchema } from "@/models/mcp.schema";+import { handleAddJob } from "@/lib/mcp/tools/addJob";++// Sequential, not Promise.all: entity resolution is check-then-act, and+// SQLite serializes writes anyway — parallelism here only buys races.+export async function handleAddJobsBatch(+ input: { jobs: Array<z.infer<typeof McpAddJobSchema>> },+ userId: string,+ tokenName: string,+): Promise<{ content: Array<{ type: "text"; text: string }> }> {+ const total = input.jobs.length;+ const lines: string[] = [];++ for (let i = 0; i < total; i++) {+ const item = input.jobs[i];+ const label = `[${i + 1}/${total}] ${item.company} — ${item.jobTitle}`;+ let text: string;+ try {+ const result = await handleAddJob(item, userId, tokenName);+ text = result.content[0].text;+ } catch (err: any) {+ text = `Error: ${err?.message ?? "Unknown error"}`;+ }+ lines.push(`${label}: ${text}`);++ if (text.startsWith("Rate limit exceeded")) {+ const remaining = total - (i + 1);+ if (remaining > 0) {+ lines.push(+ `Stopped after the rate limit — ${remaining} item(s) not attempted. ` ++ `Retry them once the window resets.`,+ );+ }+ break;+ }+ }++ return { content: [{ type: "text", text: lines.join("\n\n") }] };+}diff --git a/src/lib/mcp/tools/saveMatchResultsBatch.ts b/src/lib/mcp/tools/saveMatchResultsBatch.tsnew file mode 100644index 0000000..c12f505--- /dev/null+++ b/src/lib/mcp/tools/saveMatchResultsBatch.ts@@ -0,0 +1,38 @@+import { z } from "zod";+import { McpSaveMatchResultSchema } from "@/models/mcp.schema";+import { handleSaveMatchResult } from "@/lib/mcp/tools/saveMatchResult";++export async function handleSaveMatchResultsBatch(+ input: { results: Array<z.infer<typeof McpSaveMatchResultSchema>> },+ userId: string,+ tokenName: string,+): Promise<{ content: Array<{ type: "text"; text: string }> }> {+ const total = input.results.length;+ const lines: string[] = [];++ for (let i = 0; i < total; i++) {+ const item = input.results[i];+ const label = `[${i + 1}/${total}] ${item.jobId}`;+ let text: string;+ try {+ const result = await handleSaveMatchResult(item, userId, tokenName);+ text = result.content[0].text;+ } catch (err: any) {+ text = `Error: ${err?.message ?? "Unknown error"}`;+ }+ lines.push(`${label}: ${text}`);++ if (text.startsWith("Rate limit exceeded")) {+ const remaining = total - (i + 1);+ if (remaining > 0) {+ lines.push(+ `Stopped after the rate limit — ${remaining} item(s) not attempted. ` ++ `Retry them once the window resets.`,+ );+ }+ break;+ }+ }++ return { content: [{ type: "text", text: lines.join("\n\n") }] };+}diff --git a/src/models/mcp.schema.ts b/src/models/mcp.schema.tsindex 7b0f551..3de5e3e 100644--- a/src/models/mcp.schema.ts+++ b/src/models/mcp.schema.ts@@ -194,3 +194,43 @@ export const McpUpdateJobSchema = z.object({});export type McpUpdateJobInput = z.infer<typeof McpUpdateJobSchema>;++// Batch wrappers — the per-item shapes are reused verbatim so the batch and+// single-item tools can never drift apart.+export const McpAddJobsBatchInputShape = {+ jobs: z+ .array(z.object(McpAddJobInputShape))+ .min(1)+ .max(APP_CONSTANTS.MCP_BATCH_MAX_ITEMS)+ .describe(+ `Up to ${APP_CONSTANTS.MCP_BATCH_MAX_ITEMS} jobs, each with the same ` ++ `fields as add_job. Processed in order; each item consumes one unit ` ++ `of the MCP rate-limit budget.`,+ ),+};++export const McpAddJobsBatchSchema = z.object({+ jobs: z.array(McpAddJobSchema).min(1).max(APP_CONSTANTS.MCP_BATCH_MAX_ITEMS),+});+export type McpAddJobsBatchInput = z.infer<typeof McpAddJobsBatchSchema>;++export const McpSaveMatchResultsBatchInputShape = {+ results: z+ .array(z.object(McpSaveMatchResultInputShape))+ .min(1)+ .max(APP_CONSTANTS.MCP_BATCH_MAX_ITEMS)+ .describe(+ `Up to ${APP_CONSTANTS.MCP_BATCH_MAX_ITEMS} match analyses, each with ` ++ `the same fields as save_match_result.`,+ ),+};++export const McpSaveMatchResultsBatchSchema = z.object({+ results: z+ .array(McpSaveMatchResultSchema)+ .min(1)+ .max(APP_CONSTANTS.MCP_BATCH_MAX_ITEMS),+});+export type McpSaveMatchResultsBatchInput = z.infer<+ typeof McpSaveMatchResultsBatchSchema+>;