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: add MCP save_match_result tool and job-match directive for add_job
Khuram Niaz3c349198011b
diff --git a/__tests__/atsBoardUrl.spec.ts b/__tests__/atsBoardUrl.spec.tsindex c6a63f0..d050d26 100644--- a/__tests__/atsBoardUrl.spec.ts+++ b/__tests__/atsBoardUrl.spec.ts@@ -15,8 +15,8 @@ describe("companyBoardUrl", () => {);});- it("uses the US Lever host when host is explicitly us", () => {- expect(companyBoardUrl("lever", { token: "acme", host: "us" })).toBe(+ it("uses the US Lever host when host is explicitly default", () => {+ expect(companyBoardUrl("lever", { token: "acme", host: "default" })).toBe(`${APP_CONSTANTS.LEVER_JOB_URL}/acme`,);});diff --git a/__tests__/mcpAddJob.spec.ts b/__tests__/mcpAddJob.spec.tsnew file mode 100644index 0000000..2cbdd4f--- /dev/null+++ b/__tests__/mcpAddJob.spec.ts@@ -0,0 +1,155 @@+import { handleAddJob } from "@/lib/mcp/tools/addJob";+import { createJobFromNames } from "@/lib/jobs/createJobFromNames";+import { getDefaultResumeForUser } from "@/lib/jobs/getDefaultResumeForUser";+import { preprocessResume } from "@/lib/ai/tools/preprocessing";+import { checkMcpRateLimit } from "@/lib/mcp/rate-limit";++vi.mock("@/lib/jobs/createJobFromNames", () => ({+ createJobFromNames: vi.fn(),+}));++vi.mock("@/lib/jobs/getDefaultResumeForUser", () => ({+ getDefaultResumeForUser: vi.fn(),+}));++vi.mock("@/lib/ai/tools/preprocessing", () => ({+ preprocessResume: vi.fn(),+}));++vi.mock("@/lib/mcp/rate-limit", () => ({+ checkMcpRateLimit: vi.fn(() => ({ allowed: true, resetIn: 0 })),+}));++const longDescription = "a".repeat(250);+const shortDescription = "Short JD.";++const baseInput = {+ company: "Acme",+ jobTitle: "Engineer",+ jobDescription: longDescription,+};++describe("handleAddJob match gating", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("appends resume text + save_match_result directive when created + substantive + default resume usable", async () => {+ (createJobFromNames as any).mockResolvedValue({+ created: true,+ jobId: "job-1",+ resolutions: [],+ message: "Created Acme; Created Engineer. Job created (id: job-1).",+ });+ (getDefaultResumeForUser as any).mockResolvedValue({ id: "resume-1", title: "My Resume" });+ (preprocessResume as any).mockResolvedValue({+ success: true,+ data: { normalizedText: "NORMALIZED RESUME TEXT", metadata: {}, isValid: true },+ });++ const result = await handleAddJob(baseInput as any, "user-1", "my-token");+ const text = result.content[0].text;++ expect(text).toContain("Job created (id: job-1)");+ expect(text).toContain("NORMALIZED RESUME TEXT");+ expect(text).toContain("job-1");+ expect(text).toContain("save_match_result");+ expect(text).toContain("SCORES: match=<0-100> recommendation=<strong|good|partial|weak>");+ // Directive requests the four structured sections (richer match body).+ expect(text).toContain("## Overall Fit");+ expect(text).toContain("## Key Strengths");+ expect(text).toContain("## Gaps / Risks");+ expect(text).toContain("## Recommendation");+ // Directive threads the resumeId back for save_match_result provenance.+ expect(text).toContain('"resumeId": "resume-1"');+ });++ it("adds a short-description note and no directive when description is under the threshold", async () => {+ (createJobFromNames as any).mockResolvedValue({+ created: true,+ jobId: "job-1",+ resolutions: [],+ message: "Created Acme; Created Engineer. Job created (id: job-1).",+ });++ const result = await handleAddJob(+ { ...baseInput, jobDescription: shortDescription } as any,+ "user-2",+ "my-token",+ );+ const text = result.content[0].text;++ expect(text).toContain("Description too short to match");+ expect(text).not.toContain("save_match_result");+ expect(getDefaultResumeForUser).not.toHaveBeenCalled();+ });++ it("adds an actionable note when no default resume is set", async () => {+ (createJobFromNames as any).mockResolvedValue({+ created: true,+ jobId: "job-1",+ resolutions: [],+ message: "Created Acme; Created Engineer. Job created (id: job-1).",+ });+ (getDefaultResumeForUser as any).mockResolvedValue(null);++ const result = await handleAddJob(baseInput as any, "user-3", "my-token");+ const text = result.content[0].text;++ expect(text).toContain("No default resume set");+ expect(text).not.toContain("save_match_result");+ expect(preprocessResume).not.toHaveBeenCalled();+ });++ it("adds a distinct note when the default resume exists but fails preprocessing", async () => {+ (createJobFromNames as any).mockResolvedValue({+ created: true,+ jobId: "job-1",+ resolutions: [],+ message: "Created Acme; Created Engineer. Job created (id: job-1).",+ });+ (getDefaultResumeForUser as any).mockResolvedValue({ id: "resume-1", title: "My Resume" });+ (preprocessResume as any).mockResolvedValue({+ success: false,+ error: { code: "TOO_SHORT", message: "Resume is too short" },+ });++ const result = await handleAddJob(baseInput as any, "user-4", "my-token");+ const text = result.content[0].text;++ expect(text).toContain("Default resume couldn't be used for matching");+ expect(text).not.toContain("No default resume set");+ expect(text).not.toContain("save_match_result");+ });++ it("does not offer a match on a duplicate, and explains why", async () => {+ (createJobFromNames as any).mockResolvedValue({+ created: false,+ duplicateOf: { id: "job-existing", title: "Engineer", company: "Acme" },+ resolutions: [],+ message: 'Duplicate detected — existing job "Engineer" at "Acme" (id: job-existing).',+ });++ const result = await handleAddJob(baseInput as any, "user-5", "my-token");+ const text = result.content[0].text;++ expect(text).toContain("Duplicate detected");+ expect(text).toContain("No match offered for duplicates");+ expect(getDefaultResumeForUser).not.toHaveBeenCalled();+ expect(preprocessResume).not.toHaveBeenCalled();+ });++ it("returns a rate-limit message and never creates a job when the limit is exceeded", async () => {+ (checkMcpRateLimit as any).mockReturnValueOnce({+ allowed: false,+ resetIn: 60000,+ });++ const result = await handleAddJob(baseInput as any, "user-6", "my-token");+ const text = result.content[0].text;++ expect(text).toContain("Rate limit exceeded");+ expect(text).toContain("60s");+ expect(createJobFromNames).not.toHaveBeenCalled();+ });+});diff --git a/__tests__/saveMatchResult.spec.ts b/__tests__/saveMatchResult.spec.tsnew file mode 100644index 0000000..37cce2a--- /dev/null+++ b/__tests__/saveMatchResult.spec.ts@@ -0,0 +1,217 @@+import { handleSaveMatchResult } from "@/lib/mcp/tools/saveMatchResult";+import { checkMcpRateLimit } from "@/lib/mcp/rate-limit";+import { PrismaClient } from "@prisma/client";++const prisma = new PrismaClient();++vi.mock("@prisma/client", () => {+ const mPrismaClient = {+ job: { update: vi.fn() },+ user: { findUnique: vi.fn() },+ resume: { findFirst: vi.fn() },+ };+ return { PrismaClient: vi.fn(function () { return mPrismaClient; }) };+});++vi.mock("@/lib/mcp/rate-limit", () => ({+ checkMcpRateLimit: vi.fn(() => ({ allowed: true, resetIn: 0 })),+}));++const validMatchText =+ "SCORES: match=78 recommendation=good\n\n## Strengths\nSolid backend experience.";++describe("handleSaveMatchResult", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ (prisma.user.findUnique as any).mockResolvedValue({+ defaultResumeId: "resume-1",+ });+ (prisma.resume.findFirst as any).mockResolvedValue({+ id: "resume-1",+ title: "My Resume",+ });+ (prisma.job.update as any).mockResolvedValue({ id: "job-1" });+ });++ it("parses a valid matchText and persists clamped score + shaped matchData", async () => {+ const result = await handleSaveMatchResult(+ { jobId: "job-1", matchText: validMatchText },+ "user-1",+ "my-token",+ );++ expect(prisma.job.update).toHaveBeenCalledWith({+ where: { id: "job-1", userId: "user-1", createdVia: { not: null } },+ data: {+ matchScore: 78,+ matchData: expect.any(String),+ },+ });++ const call = (prisma.job.update as any).mock.calls[0][0];+ const matchData = JSON.parse(call.data.matchData);+ expect(matchData).toMatchObject({+ matchScore: 78,+ recommendation: "good match",+ resumeId: "resume-1",+ resumeTitle: "My Resume",+ provider: "mcp",+ model: "my-token",+ analyzed: true,+ });+ expect(matchData.body).toContain("Solid backend experience.");+ expect(typeof matchData.matchedAt).toBe("string");++ expect(result.content[0].text).toContain("Match saved for job job-1");+ expect(result.content[0].text).toContain("good match");+ expect(result.content[0].text).toContain("78");+ });++ it("returns a parse-error message when matchText has no SCORES line", async () => {+ const result = await handleSaveMatchResult(+ { jobId: "job-1", matchText: "Just some prose with no scores line at all here." },+ "user-2",+ "my-token",+ );++ expect(result.content[0].text).toContain("Could not parse a SCORES line");+ expect(prisma.job.update).not.toHaveBeenCalled();+ });++ it("returns a not-found/not-eligible message on P2025 (non-owned or non-MCP-created job)", async () => {+ (prisma.job.update as any).mockRejectedValue({ code: "P2025" });++ const result = await handleSaveMatchResult(+ { jobId: "someone-elses-job", matchText: validMatchText },+ "user-3",+ "my-token",+ );++ expect(result.content[0].text).toBe(+ "Job not found, not owned by this token's user, or not eligible for a match via MCP.",+ );+ });++ it("overwrites a prior match (last-write-wins, no pre-check)", async () => {+ await handleSaveMatchResult(+ { jobId: "job-1", matchText: validMatchText },+ "user-4",+ "my-token",+ );+ await handleSaveMatchResult(+ {+ jobId: "job-1",+ matchText: "SCORES: match=40 recommendation=weak\n\nUpdated analysis.",+ },+ "user-4",+ "my-token",+ );++ expect(prisma.job.update).toHaveBeenCalledTimes(2);+ const secondCall = (prisma.job.update as any).mock.calls[1][0];+ expect(secondCall.data.matchScore).toBe(40);+ });++ it("omits resumeId/resumeTitle when no default resume is set (best-effort)", async () => {+ (prisma.user.findUnique as any).mockResolvedValue({ defaultResumeId: null });++ await handleSaveMatchResult(+ { jobId: "job-1", matchText: validMatchText },+ "user-5",+ "my-token",+ );++ const call = (prisma.job.update as any).mock.calls[0][0];+ const matchData = JSON.parse(call.data.matchData);+ expect(matchData.resumeId).toBeUndefined();+ expect(matchData.resumeTitle).toBeUndefined();+ });++ it("prefers the echoed resumeId for provenance over the current default", async () => {+ (prisma.resume.findFirst as any).mockResolvedValue({+ id: "resume-scored",+ title: "Scored Resume",+ });++ await handleSaveMatchResult(+ { jobId: "job-1", resumeId: "resume-scored", matchText: validMatchText },+ "user-6",+ "my-token",+ );++ expect(prisma.resume.findFirst).toHaveBeenCalledWith({+ where: { id: "resume-scored", profile: { userId: "user-6" } },+ select: { id: true, title: true },+ });+ // Echoed id resolved, so the default lookup is skipped entirely.+ expect(prisma.user.findUnique).not.toHaveBeenCalled();++ const call = (prisma.job.update as any).mock.calls[0][0];+ const matchData = JSON.parse(call.data.matchData);+ expect(matchData.resumeId).toBe("resume-scored");+ expect(matchData.resumeTitle).toBe("Scored Resume");+ });++ it("falls back to the current default when an echoed resumeId no longer resolves", async () => {+ // Echoed id doesn't resolve; default lookup then succeeds.+ (prisma.resume.findFirst as any)+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({ id: "resume-1", title: "My Resume" });++ await handleSaveMatchResult(+ { jobId: "job-1", resumeId: "stale-resume", matchText: validMatchText },+ "user-7",+ "my-token",+ );++ expect(prisma.user.findUnique).toHaveBeenCalled();+ const call = (prisma.job.update as any).mock.calls[0][0];+ const matchData = JSON.parse(call.data.matchData);+ expect(matchData.resumeId).toBe("resume-1");+ });++ it("returns a rate-limit message and never persists when the limit is exceeded", async () => {+ (checkMcpRateLimit as any).mockReturnValueOnce({+ allowed: false,+ resetIn: 60000,+ });++ const result = await handleSaveMatchResult(+ { jobId: "job-1", matchText: validMatchText },+ "user-8",+ "my-token",+ );++ expect(result.content[0].text).toContain("Rate limit exceeded");+ expect(prisma.job.update).not.toHaveBeenCalled();+ });++ it("clamps an out-of-range score into 0-100", async () => {+ await handleSaveMatchResult(+ {+ jobId: "job-1",+ matchText: "SCORES: match=150 recommendation=strong\n\nOverqualified.",+ },+ "user-9",+ "my-token",+ );++ const call = (prisma.job.update as any).mock.calls[0][0];+ expect(call.data.matchScore).toBe(100);+ const matchData = JSON.parse(call.data.matchData);+ expect(matchData.matchScore).toBe(100);+ expect(matchData.recommendation).toBe("strong match");+ });++ it("surfaces a generic error message on a non-P2025 DB failure", async () => {+ (prisma.job.update as any).mockRejectedValue({ message: "connection reset" });++ const result = await handleSaveMatchResult(+ { jobId: "job-1", matchText: validMatchText },+ "user-10",+ "my-token",+ );++ expect(result.content[0].text).toContain("Error: connection reset");+ });+});diff --git a/src/actions/profile.actions.ts b/src/actions/profile.actions.tsindex 4cc1203..9b876ba 100644--- a/src/actions/profile.actions.ts+++ b/src/actions/profile.actions.ts@@ -14,6 +14,7 @@ import {} from "@/models/skills.schema";import { getCurrentUser } from "@/utils/user.utils";import { APP_CONSTANTS } from "@/lib/constants";+import { resumeDetailInclude } from "@/lib/jobs/resumeDetailInclude";import {buildInsufficientSectionsMessage,hasMinResumeSections,@@ -198,29 +199,7 @@ export const getResumeById = async (id: resumeId,profile: { userId: user.id },},- include: {- ContactInfo: true,- File: true,- ResumeSections: {- include: {- summary: true,- workExperiences: {- include: {- jobTitle: true,- Company: true,- location: true,- },- },- educations: {- include: {- location: true,- },- },- licenseOrCertifications: true,- skills: { include: { Tag: true } },- },- },- },+ include: resumeDetailInclude,});return { data: resume, success: true };} catch (error) {diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.tsindex 9edc4fa..5d6202a 100644--- a/src/app/api/mcp/route.ts+++ b/src/app/api/mcp/route.ts@@ -6,9 +6,12 @@ import {McpAddJobSchema,McpAddQuestionInputShape,McpAddQuestionSchema,+ McpSaveMatchResultInputShape,+ McpSaveMatchResultSchema,} 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";function isMcpEnabled(): boolean {const env = process.env.MCP_ENABLED;@@ -91,6 +94,34 @@ async function handler(req: Request): Promise<Response> {},);+ server.tool(+ "save_match_result",+ "Persist a job-fit match analysis (produced by you, the agent) against a job previously created with add_job. Call this after add_job hands you a match directive.",+ McpSaveMatchResultInputShape,+ async (rawInput) => {+ if (!auth.scopes.includes("jobs:write")) {+ return {+ content: [+ {+ type: "text" as const,+ text: "Insufficient scope. Required: jobs:write",+ },+ ],+ };+ }+ const parsed = McpSaveMatchResultSchema.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 handleSaveMatchResult(parsed.data, userId, tokenName);+ },+ );+const transport = new WebStandardStreamableHTTPServerTransport({sessionIdGenerator: undefined, // stateless modeenableJsonResponse: true, // return plain JSON instead of SSE streamdiff --git a/src/lib/constants.ts b/src/lib/constants.tsindex ab1f253..7592c1d 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -96,6 +96,8 @@ export const APP_CONSTANTS = {MCP_RATE_LIMIT_WINDOW_MS: 60 * 60 * 1000,MCP_DEFAULT_JOB_TYPE: "Full-time",MCP_DEFAULT_STATUS: "draft",+ MCP_MATCH_MIN_DESCRIPTION_LENGTH: 200,+ MCP_MATCH_PROVIDER_MARKER: "mcp",// File uploadsUPLOADS_DIR: process.env.NODE_ENV !== "production" ? "data" : "/data",diff --git a/src/lib/jobs/getDefaultResumeForUser.ts b/src/lib/jobs/getDefaultResumeForUser.tsnew file mode 100644index 0000000..4b66569--- /dev/null+++ b/src/lib/jobs/getDefaultResumeForUser.ts@@ -0,0 +1,28 @@+import prisma from "@/lib/db";+import { Resume } from "@/models/profile.model";+import { resumeDetailInclude } from "@/lib/jobs/resumeDetailInclude";++// Session-less equivalent of getDefaultResumeById + getResumeById, for the+// MCP path where there is no auth() session to derive the user from — see+// docs/plans/feature-mcp-add-job-match.md ("Session-less constraint").+export async function getDefaultResumeForUser(+ userId: string,+): Promise<Resume | null> {+ const user = await prisma.user.findUnique({+ where: { id: userId },+ select: { defaultResumeId: true },+ });+ if (!user?.defaultResumeId) return null;++ const resume = await prisma.resume.findFirst({+ where: { id: user.defaultResumeId, profile: { userId } },+ include: resumeDetailInclude,+ });+ if (!resume) return null;++ // Prisma's generated shape is structurally what preprocessResume reads+ // (ContactInfo, ResumeSections, title) but isn't nominally the profile.model+ // Resume type (e.g. sectionType is a plain string vs. the SectionType enum).+ // Mirrors the in-app path: getResumeById returns `any` to the same effect.+ return resume as unknown as Resume;+}diff --git a/src/lib/jobs/resumeDetailInclude.ts b/src/lib/jobs/resumeDetailInclude.tsnew file mode 100644index 0000000..11050d6--- /dev/null+++ b/src/lib/jobs/resumeDetailInclude.ts@@ -0,0 +1,29 @@+// Shared Prisma `include` for a full resume with relations, as consumed by+// preprocessResume/convertResumeToText. Extracted so both the session-scoped+// getResumeById (profile.actions.ts) and the userId-scoped+// getDefaultResumeForUser (MCP path) stay in sync. profile.actions.ts has+// "use server" at the top, which only allows async-function exports, so this+// object can't live there directly.+export const resumeDetailInclude = {+ ContactInfo: true,+ File: true,+ ResumeSections: {+ include: {+ summary: true,+ workExperiences: {+ include: {+ jobTitle: true,+ Company: true,+ location: true,+ },+ },+ educations: {+ include: {+ location: true,+ },+ },+ licenseOrCertifications: true,+ skills: { include: { Tag: true } },+ },+ },+} as const;diff --git a/src/lib/mcp/tools/addJob.ts b/src/lib/mcp/tools/addJob.tsindex 0032460..517c715 100644--- a/src/lib/mcp/tools/addJob.ts+++ b/src/lib/mcp/tools/addJob.ts@@ -1,7 +1,10 @@import { z } from "zod";+import { APP_CONSTANTS } from "@/lib/constants";import { McpAddJobSchema } from "@/models/mcp.schema";import { createJobFromNames } from "@/lib/jobs/createJobFromNames";import { checkMcpRateLimit } from "@/lib/mcp/rate-limit";+import { getDefaultResumeForUser } from "@/lib/jobs/getDefaultResumeForUser";+import { preprocessResume } from "@/lib/ai/tools/preprocessing";export const addJobToolDefinition = {name: "add_job",@@ -10,6 +13,38 @@ export const addJobToolDefinition = {inputSchema: McpAddJobSchema,} as const;+function buildMatchDirective(+ jobId: string,+ resumeId: string,+ normalizedResumeText: string,+): string {+ return (+ `You just added a job to JobSync (job id: ${jobId}). Produce a job-fit ` ++ `match of this job against the user's default resume, shown below.\n\n` ++ `DEFAULT RESUME (normalized):\n${normalizedResumeText}\n\n` ++ `INSTRUCTIONS:\n` ++ `- Analyze fit between the resume above and the job description you just\n` ++ ` submitted in this same add_job call.\n` ++ `- Use ONLY the resume and that job description. Do not invent employers,\n` ++ ` skills, titles, dates, or credentials that are not present in them.\n` ++ `- Score honestly. If the resume lacks the information needed to judge fit,\n` ++ ` still emit a SCORES line with a low score and a "weak" recommendation and\n` ++ ` say what is missing — do NOT fabricate a match.\n` ++ `- Produce, in this exact order:\n` ++ ` 1. A single first line, exactly:\n` ++ ` SCORES: match=<0-100> recommendation=<strong|good|partial|weak>\n` ++ ` 2. A markdown body with these four sections, each at least a few\n` ++ ` sentences of specific, evidence-based analysis (cite concrete\n` ++ ` skills, titles, and years from the resume and job description):\n` ++ ` ## Overall Fit\n` ++ ` ## Key Strengths\n` ++ ` ## Gaps / Risks\n` ++ ` ## Recommendation\n` ++ `- Then call save_match_result with:\n` ++ ` { "jobId": "${jobId}", "resumeId": "${resumeId}", "matchText": "<the full SCORES line + markdown body>" }`+ );+}+export async function handleAddJob(input: z.infer<typeof McpAddJobSchema>,userId: string,@@ -28,7 +63,43 @@ export async function handleAddJob({ ...input, createdVia: tokenName },userId,);- return { content: [{ type: "text", text: result.message }] };++ if (!result.created || !result.jobId) {+ const text =+ result.message ++ " No match offered for duplicates — you can match it in the web app.";+ return { content: [{ type: "text", text }] };+ }++ if (input.jobDescription.length < APP_CONSTANTS.MCP_MATCH_MIN_DESCRIPTION_LENGTH) {+ const text =+ result.message ++ " Description too short to match (under 200 characters) — the job was still added.";+ return { content: [{ type: "text", text }] };+ }++ const resume = await getDefaultResumeForUser(userId);+ if (!resume) {+ const text =+ result.message ++ " No default resume set — set one in Profile → Resumes to enable automatic matching.";+ return { content: [{ type: "text", text }] };+ }++ const pre = await preprocessResume(resume);+ if (!pre.success) {+ const text =+ result.message ++ " Default resume couldn't be used for matching (it may be too short or missing content) — check it in Profile → Resumes.";+ return { content: [{ type: "text", text }] };+ }++ const directive = buildMatchDirective(+ result.jobId,+ resume.id!,+ pre.data.normalizedText,+ );+ return { content: [{ type: "text", text: `${result.message}\n\n${directive}` }] };} catch (err: any) {return {content: [{ type: "text", text: `Error: ${err?.message ?? "Unknown error"}` }],diff --git a/src/lib/mcp/tools/saveMatchResult.ts b/src/lib/mcp/tools/saveMatchResult.tsnew file mode 100644index 0000000..c2ee247--- /dev/null+++ b/src/lib/mcp/tools/saveMatchResult.ts@@ -0,0 +1,115 @@+import { z } from "zod";+import prisma from "@/lib/db";+import { APP_CONSTANTS } from "@/lib/constants";+import { McpSaveMatchResultSchema } from "@/models/mcp.schema";+import { checkMcpRateLimit } from "@/lib/mcp/rate-limit";+import { parseJobMatch } from "@/lib/ai/jobMatch/parse";+import type { JobMatchData } from "@/models/ai.schemas";++export const saveMatchResultToolDefinition = {+ name: "save_match_result",+ description:+ "Persist a job-fit match analysis (produced by you, the agent) against a job previously created with add_job. Call this after add_job hands you a match directive.",+ inputSchema: McpSaveMatchResultSchema,+} as const;++export async function handleSaveMatchResult(+ input: z.infer<typeof McpSaveMatchResultSchema>,+ userId: string,+ tokenName: string,+): Promise<{ content: Array<{ type: "text"; text: string }> }> {+ // Shares add_job's bucket by design. At the exact window boundary a match can+ // be computed but rejected here; accepted — the user can retry or match+ // in-app, and nothing is left in a corrupt state.+ 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.` }],+ };+ }++ const parsed = parseJobMatch(input.matchText);+ if (!parsed.scores) {+ return {+ content: [+ {+ type: "text",+ text:+ "Could not parse a SCORES line. Include a leading 'SCORES: " ++ "match=<0-100> recommendation=<strong|good|partial|weak>' line.",+ },+ ],+ };+ }++ // Provenance needs only id + title, so avoid the full resume graph that+ // getDefaultResumeForUser loads for preprocessing. Prefer the resumeId+ // add_job handed the agent (the resume actually scored against); the+ // profile.userId scope bounds it to the user's own resumes. Fall back to the+ // current default if the agent didn't echo an id or it no longer resolves.+ let resume =+ input.resumeId != null+ ? await prisma.resume.findFirst({+ where: { id: input.resumeId, profile: { userId } },+ select: { id: true, title: true },+ })+ : null;+ if (!resume) {+ const user = await prisma.user.findUnique({+ where: { id: userId },+ select: { defaultResumeId: true },+ });+ resume = user?.defaultResumeId+ ? await prisma.resume.findFirst({+ where: { id: user.defaultResumeId, profile: { userId } },+ select: { id: true, title: true },+ })+ : null;+ }++ const matchData: JobMatchData = {+ matchScore: parsed.scores.matchScore,+ recommendation: parsed.scores.recommendation,+ body: parsed.body,+ resumeId: resume?.id,+ resumeTitle: resume?.title,+ matchedAt: new Date().toISOString(),+ provider: APP_CONSTANTS.MCP_MATCH_PROVIDER_MARKER,+ model: tokenName,+ analyzed: true,+ };++ try {+ await prisma.job.update({+ where: { id: input.jobId, userId, createdVia: { not: null } },+ data: {+ matchScore: parsed.scores.matchScore,+ matchData: JSON.stringify(matchData),+ },+ });+ } catch (error: any) {+ if (error?.code === "P2025") {+ return {+ content: [+ {+ type: "text",+ text: "Job not found, not owned by this token's user, or not eligible for a match via MCP.",+ },+ ],+ };+ }+ return {+ content: [{ type: "text", text: `Error: ${error?.message ?? "Unknown error"}` }],+ };+ }++ return {+ content: [+ {+ type: "text",+ text: `Match saved for job ${input.jobId}: ${parsed.scores.recommendation} (score ${parsed.scores.matchScore}).`,+ },+ ],+ };+}diff --git a/src/models/mcp.schema.ts b/src/models/mcp.schema.tsindex cb10797..4c50d85 100644--- a/src/models/mcp.schema.ts+++ b/src/models/mcp.schema.ts@@ -45,3 +45,23 @@ export const McpAddQuestionInputShape = {export const McpAddQuestionSchema = z.object(McpAddQuestionInputShape);export type McpAddQuestionInput = z.infer<typeof McpAddQuestionSchema>;++// Raw input shape for MCP tool registration (no transforms needed)+export const McpSaveMatchResultInputShape = {+ jobId: z.string().min(1).describe("The id of the job returned by add_job."),+ resumeId: z+ .string()+ .min(1)+ .optional()+ .describe(+ "The id of the resume this match was scored against, exactly as given " ++ "in the add_job directive. Omit only if the directive had none.",+ ),+ matchText: z.string().min(20).describe(+ "Your full match analysis: a leading 'SCORES: match=<0-100> " ++ "recommendation=<strong|good|partial|weak>' line, then a markdown body.",+ ),+};++export const McpSaveMatchResultSchema = z.object(McpSaveMatchResultInputShape);+export type McpSaveMatchResultInput = z.infer<typeof McpSaveMatchResultSchema>;