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 find_job and update_job tools
Khuram Niaz527d3f22a2a8
diff --git a/__tests__/mcpFindJob.spec.ts b/__tests__/mcpFindJob.spec.tsnew file mode 100644index 0000000..4d64efe--- /dev/null+++ b/__tests__/mcpFindJob.spec.ts@@ -0,0 +1,132 @@+import { handleFindJob } from "@/lib/mcp/tools/findJob";+import { findExistingJobByUrl } from "@/lib/jobs/jobDedupe";+import { checkMcpRateLimit } from "@/lib/mcp/rate-limit";+import { PrismaClient } from "@prisma/client";++const prisma = new PrismaClient();++vi.mock("@prisma/client", () => {+ const mPrismaClient = { job: { findFirst: vi.fn() } };+ return { PrismaClient: vi.fn(function () { return mPrismaClient; }) };+});++vi.mock("@/lib/jobs/jobDedupe", () => ({+ findExistingJobByUrl: vi.fn(),+}));++vi.mock("@/lib/mcp/rate-limit", () => ({+ checkMcpRateLimit: vi.fn(() => ({ allowed: true, resetIn: 0 })),+}));++const url = "https://example.com/jobs/1";++describe("handleFindJob", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ (checkMcpRateLimit as any).mockReturnValue({ allowed: true, resetIn: 0 });+ });++ it("reports no match when nothing exists for the URL", async () => {+ (findExistingJobByUrl as any).mockResolvedValue(null);++ const result = await handleFindJob({ jobUrl: url }, "user-1");++ expect(result.content[0].text).toContain("No saved job matches that URL");+ expect(result.content[0].text).toContain("add_job");+ });++ it("returns the existing job id, status, completeness and current tags", async () => {+ (findExistingJobByUrl as any).mockResolvedValue({+ id: "job-1",+ title: "Engineer",+ company: "Acme",+ });+ (prisma.job.findFirst as any).mockResolvedValue({+ id: "job-1",+ descriptionCompleteness: "title-only",+ matchScore: null,+ createdVia: "my-token",+ Status: { value: "draft" },+ tags: [{ label: "React" }, { label: "Remote" }],+ });++ const result = await handleFindJob({ jobUrl: url }, "user-1");+ const text = result.content[0].text;++ expect(text).toContain("job-1");+ expect(text).toContain("Engineer");+ expect(text).toContain("Acme");+ expect(text).toContain("draft");+ expect(text).toContain("title-only");+ expect(text).toContain("React, Remote");+ expect(text).toContain("update_job");+ // Tags are replaced wholesale by update_job, so an agent that doesn't+ // see the current list here would silently wipe it out.+ expect(text).toContain("replaced wholesale");+ });++ it("reports 'none' when the existing job has no tags", async () => {+ (findExistingJobByUrl as any).mockResolvedValue({+ id: "job-1",+ title: "Engineer",+ company: "Acme",+ });+ (prisma.job.findFirst as any).mockResolvedValue({+ id: "job-1",+ descriptionCompleteness: "full",+ matchScore: 80,+ createdVia: "my-token",+ Status: { value: "applied" },+ tags: [],+ });++ const result = await handleFindJob({ jobUrl: url }, "user-1");+ expect(result.content[0].text).toContain("tags: none");+ });++ it("scopes the detail lookup to the caller", async () => {+ (findExistingJobByUrl as any).mockResolvedValue({+ id: "job-1",+ title: "Engineer",+ company: "Acme",+ });+ (prisma.job.findFirst as any).mockResolvedValue(null);++ await handleFindJob({ jobUrl: url }, "user-1");++ expect(prisma.job.findFirst).toHaveBeenCalledWith(+ expect.objectContaining({+ where: { id: "job-1", userId: "user-1" },+ }),+ );+ });++ it("says the job is not MCP-updatable when createdVia is null", async () => {+ (findExistingJobByUrl as any).mockResolvedValue({+ id: "job-1",+ title: "Engineer",+ company: "Acme",+ });+ (prisma.job.findFirst as any).mockResolvedValue({+ id: "job-1",+ descriptionCompleteness: null,+ matchScore: 70,+ createdVia: null,+ Status: { value: "applied" },+ tags: [],+ });++ const result = await handleFindJob({ jobUrl: url }, "user-1");++ expect(result.content[0].text).toContain("cannot be updated via MCP");+ });++ it("short-circuits when rate limited", async () => {+ (checkMcpRateLimit as any).mockReturnValue({ allowed: false, resetIn: 3000 });++ const result = await handleFindJob({ jobUrl: url }, "user-1");++ expect(result.content[0].text).toContain("Rate limit exceeded");+ expect(findExistingJobByUrl).not.toHaveBeenCalled();+ });+});diff --git a/__tests__/mcpUpdateJob.spec.ts b/__tests__/mcpUpdateJob.spec.tsnew file mode 100644index 0000000..ccb07f6--- /dev/null+++ b/__tests__/mcpUpdateJob.spec.ts@@ -0,0 +1,109 @@+import { handleUpdateJob } from "@/lib/mcp/tools/updateJob";+import { updateJobFromNames } from "@/lib/jobs/updateJobFromNames";+import { buildMatchOffer } from "@/lib/mcp/tools/matchDirective";+import { checkMcpRateLimit } from "@/lib/mcp/rate-limit";++vi.mock("@/lib/jobs/updateJobFromNames", () => ({+ updateJobFromNames: vi.fn(),+}));++vi.mock("@/lib/mcp/tools/matchDirective", async (importOriginal) => {+ const actual: any = await importOriginal();+ return { ...actual, buildMatchOffer: vi.fn() };+});++vi.mock("@/lib/mcp/rate-limit", () => ({+ checkMcpRateLimit: vi.fn(() => ({ allowed: true, resetIn: 0 })),+}));++describe("handleUpdateJob", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ (checkMcpRateLimit as any).mockReturnValue({ allowed: true, resetIn: 0 });+ (buildMatchOffer as any).mockResolvedValue({+ kind: "directive",+ text: "DIRECTIVE calling save_match_result",+ });+ });++ it("re-offers a match when the description was enriched to full", async () => {+ (updateJobFromNames as any).mockResolvedValue({+ updated: true,+ jobId: "job-1",+ descriptionChanged: true,+ descriptionCompleteness: "full",+ resolutions: [],+ message: "Job job-1 updated. Fields changed: description.",+ });++ const result = await handleUpdateJob(+ { jobId: "job-1", jobDescription: "x".repeat(50) } as any,+ "user-1",+ );+ const text = result.content[0].text;++ expect(text).toContain("Job job-1 updated");+ expect(text).toContain("DIRECTIVE calling save_match_result");+ expect(buildMatchOffer).toHaveBeenCalledWith("job-1", "user-1", "full", "update");+ });++ it("does not re-offer a match when the description was not touched", async () => {+ (updateJobFromNames as any).mockResolvedValue({+ updated: true,+ jobId: "job-1",+ descriptionChanged: false,+ descriptionCompleteness: "full",+ resolutions: [],+ message: "Job job-1 updated. Fields changed: statusId.",+ });++ const result = await handleUpdateJob(+ { jobId: "job-1", status: "applied" } as any,+ "user-1",+ );++ expect(result.content[0].text).toBe("Job job-1 updated. Fields changed: statusId.");+ expect(buildMatchOffer).not.toHaveBeenCalled();+ });++ it("returns the helper's message unchanged when the update failed", async () => {+ (updateJobFromNames as any).mockResolvedValue({+ updated: false,+ jobId: "job-x",+ descriptionChanged: false,+ descriptionCompleteness: null,+ resolutions: [],+ message: "Job not found, not owned by this token's user, or not eligible",+ });++ const result = await handleUpdateJob(+ { jobId: "job-x", salaryRange: "$1" } as any,+ "user-1",+ );++ expect(result.content[0].text).toContain("not found");+ expect(buildMatchOffer).not.toHaveBeenCalled();+ });++ it("surfaces resolver errors as an Error: message", async () => {+ (updateJobFromNames as any).mockRejectedValue(+ new Error('Invalid jobType "Freelance". Valid values: Full-time, Part-time, Contract'),+ );++ const result = await handleUpdateJob(+ { jobId: "job-1", jobType: "Freelance" } as any,+ "user-1",+ );++ expect(result.content[0].text).toContain("Invalid jobType");+ });++ it("short-circuits when rate limited", async () => {+ (checkMcpRateLimit as any).mockReturnValue({ allowed: false, resetIn: 7000 });++ const result = await handleUpdateJob({ jobId: "job-1" } as any, "user-1");++ expect(result.content[0].text).toContain("Rate limit exceeded");+ expect(updateJobFromNames).not.toHaveBeenCalled();+ });+});diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.tsindex b483de4..af9aff0 100644--- a/src/app/api/mcp/route.ts+++ b/src/app/api/mcp/route.ts@@ -12,12 +12,18 @@ import {McpReviewResumeSchema,McpSaveResumeReviewInputShape,McpSaveResumeReviewSchema,+ McpFindJobInputShape,+ McpFindJobSchema,+ McpUpdateJobInputShape,+ McpUpdateJobSchema,} from "@/models/mcp.schema";import { handleAddJob } from "@/lib/mcp/tools/addJob";import { handleAddQuestion } from "@/lib/mcp/tools/addQuestion";import { handleSaveMatchResult } from "@/lib/mcp/tools/saveMatchResult";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";function isMcpEnabled(): boolean {const env = process.env.MCP_ENABLED;@@ -72,6 +78,52 @@ async function handler(req: Request): Promise<Response> {},);+ server.tool(+ "find_job",+ "Look up whether a job posting URL is already saved in JobSync. Call this before add_job when re-running a search, so an already-tracked posting is updated instead of duplicated.",+ McpFindJobInputShape,+ async (rawInput) => {+ if (!auth.scopes.includes("jobs:write")) {+ return {+ content: [+ { type: "text" as const, text: "Insufficient scope. Required: jobs:write" },+ ],+ };+ }+ const parsed = McpFindJobSchema.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 handleFindJob(parsed.data, userId);+ },+ );++ server.tool(+ "update_job",+ "Correct or enrich a job previously added through MCP. Only the fields you supply change. Supplying a fuller jobDescription re-classifies the posting and requests a fresh match analysis — use this instead of re-adding with allowDuplicate.",+ McpUpdateJobInputShape,+ async (rawInput) => {+ if (!auth.scopes.includes("jobs:write")) {+ return {+ content: [+ { type: "text" as const, text: "Insufficient scope. Required: jobs:write" },+ ],+ };+ }+ const parsed = McpUpdateJobSchema.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 handleUpdateJob(parsed.data, userId);+ },+ );+server.tool("add_question","Add an entry to the Question Bank. Resolves or creates tags by name. Returns a transparency report of what was matched vs. created.",diff --git a/src/lib/mcp/tools/findJob.ts b/src/lib/mcp/tools/findJob.tsnew file mode 100644index 0000000..96ae373--- /dev/null+++ b/src/lib/mcp/tools/findJob.ts@@ -0,0 +1,71 @@+import prisma from "@/lib/db";+import { findExistingJobByUrl } from "@/lib/jobs/jobDedupe";+import { checkMcpRateLimit } from "@/lib/mcp/rate-limit";++export async function handleFindJob(+ input: { jobUrl: string },+ userId: string,+): Promise<{ content: Array<{ type: "text"; text: string }> }> {+ const rateCheck = checkMcpRateLimit(userId);+ if (!rateCheck.allowed) {+ const resetSec = Math.ceil(rateCheck.resetIn / 1000);+ return {+ content: [{ type: "text", text: `Rate limit exceeded. Try again in ${resetSec}s.` }],+ };+ }++ try {+ const existing = await findExistingJobByUrl(userId, input.jobUrl);+ if (!existing) {+ return {+ content: [+ {+ type: "text",+ text: "No saved job matches that URL — call add_job to create it.",+ },+ ],+ };+ }++ const detail = await prisma.job.findFirst({+ where: { id: existing.id, userId },+ select: {+ id: true,+ descriptionCompleteness: true,+ matchScore: true,+ createdVia: true,+ Status: { select: { value: true } },+ tags: { select: { label: true } },+ },+ });++ const status = detail?.Status?.value ?? "unknown";+ const completeness = detail?.descriptionCompleteness ?? "unknown";+ const score =+ detail?.matchScore != null ? `${detail.matchScore}%` : "not scored";+ const updatable = detail?.createdVia != null;+ // update_job replaces tags wholesale (no merge) — surface the current+ // list so an agent that wants to keep them can echo them back, instead+ // of silently dropping them by omission.+ const tagsList = detail?.tags?.length+ ? detail.tags.map((t) => t.label).join(", ")+ : "none";++ const text =+ `Found existing job "${existing.title}" at "${existing.company}" ` ++ `(id: ${existing.id}, status: ${status}, description: ${completeness}, ` ++ `match: ${score}, tags: ${tagsList}). ` ++ (updatable+ ? `Call update_job with jobId "${existing.id}" to enrich or correct it ` ++ `instead of adding a duplicate. Tags are replaced wholesale, not ` ++ `merged — include the existing ones above if you want to keep them.`+ : `This job was created in the web app and cannot be updated via MCP — ` ++ `edit it there instead.`);++ return { content: [{ type: "text", text }] };+ } catch (err: any) {+ return {+ content: [{ type: "text", text: `Error: ${err?.message ?? "Unknown error"}` }],+ };+ }+}diff --git a/src/lib/mcp/tools/updateJob.ts b/src/lib/mcp/tools/updateJob.tsnew file mode 100644index 0000000..6800bc4--- /dev/null+++ b/src/lib/mcp/tools/updateJob.ts@@ -0,0 +1,43 @@+import { z } from "zod";+import { McpUpdateJobSchema } from "@/models/mcp.schema";+import { updateJobFromNames } from "@/lib/jobs/updateJobFromNames";+import { checkMcpRateLimit } from "@/lib/mcp/rate-limit";+import { buildMatchOffer, composeOfferMessage } from "@/lib/mcp/tools/matchDirective";++export async function handleUpdateJob(+ input: z.infer<typeof McpUpdateJobSchema>,+ userId: string,+): Promise<{ content: Array<{ type: "text"; text: string }> }> {+ const rateCheck = checkMcpRateLimit(userId);+ if (!rateCheck.allowed) {+ const resetSec = Math.ceil(rateCheck.resetIn / 1000);+ return {+ content: [{ type: "text", text: `Rate limit exceeded. Try again in ${resetSec}s.` }],+ };+ }++ try {+ const result = await updateJobFromNames(input, userId);++ // A fresh match is only worth requesting when the text it would be+ // scored against actually changed — a status or salary edit doesn't+ // invalidate an existing score.+ if (!result.updated || !result.descriptionChanged) {+ return { content: [{ type: "text", text: result.message }] };+ }++ const offer = await buildMatchOffer(+ result.jobId,+ userId,+ result.descriptionCompleteness ?? "title-only",+ "update",+ );+ return {+ content: [{ type: "text", text: composeOfferMessage(result.message, offer) }],+ };+ } catch (err: any) {+ return {+ content: [{ type: "text", text: `Error: ${err?.message ?? "Unknown error"}` }],+ };+ }+}diff --git a/src/models/mcp.schema.ts b/src/models/mcp.schema.tsindex 1cba0be..ddd474d 100644--- a/src/models/mcp.schema.ts+++ b/src/models/mcp.schema.ts@@ -108,3 +108,73 @@ export const McpSaveResumeReviewSchema = z.object(export type McpSaveResumeReviewInput = z.infer<typeof McpSaveResumeReviewSchema>;++// find_job — URL is the only lookup key; it's the one identifier an agent+// reliably has from a job board, and it's what add_job dedupes on.+export const McpFindJobInputShape = {+ jobUrl: z+ .string()+ .url()+ .describe(+ "Direct URL to the job posting. Matched against saved jobs using the " ++ "same canonical key as add_job's duplicate detection, so tracking " ++ "parameters and host casing don't matter.",+ ),+};++export const McpFindJobSchema = z.object(McpFindJobInputShape);+export type McpFindJobInput = z.infer<typeof McpFindJobSchema>;++// update_job — every field except jobId is optional; only supplied fields+// change. Mirrors add_job's field names exactly.+export const McpUpdateJobInputShape = {+ jobId: z+ .string()+ .min(1)+ .describe(+ "The id of the job to update, as returned by add_job or find_job. " ++ "Only jobs created through MCP can be updated.",+ ),+ company: z.string().min(1).optional(),+ jobTitle: z.string().min(1).optional(),+ jobDescription: z+ .string()+ .min(10)+ .optional()+ .describe(+ "The complete job posting text, copied in full — do not summarize. " ++ "Supplying this re-classifies the job's description completeness and, " ++ "if it is now substantive enough, a fresh match analysis is requested.",+ ),+ location: z.string().optional(),+ source: z.string().optional(),+ jobType: z.string().optional().describe("Employment type: 'Full-time', 'Part-time', or 'Contract'"),+ workplaceType: z.string().optional().describe("Work arrangement: 'Remote', 'Hybrid', or 'Onsite'"),+ // Same lowercase-preprocess treatment as add_job's status (Task 1) — the+ // SDK validates against this exact shape, so the case-insensitivity has to+ // live here too, not just on the transformed McpUpdateJobSchema.+ status: z+ .preprocess(+ (v) => (typeof v === "string" ? v.toLowerCase() : v),+ z.enum(JOB_STATUS_VALUES),+ )+ .optional()+ .describe(`Application status. One of: ${JOB_STATUS_VALUES.join(", ")}.`),+ dueDate: z.string().datetime({ offset: true }).optional(),+ applied: z.boolean().optional(),+ appliedDate: z.string().datetime({ offset: true }).optional(),+ jobUrl: z.string().url().optional(),+ salaryRange: z.string().optional(),+ tags: z+ .array(z.string())+ .optional()+ .describe("Replaces the job's tags wholesale (max 10 applied)."),+};++export const McpUpdateJobSchema = z.object({+ ...McpUpdateJobInputShape,+ dueDate: z.string().datetime({ offset: true }).optional().transform((v) => (v ? new Date(v) : undefined)),+ appliedDate: z.string().datetime({ offset: true }).optional().transform((v) => (v ? new Date(v) : undefined)),+});++export type McpUpdateJobInput = z.infer<typeof McpUpdateJobSchema>;