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 review_resume + save_resume_review tools
Khuram Niaz95633ee7b7b2
diff --git a/__tests__/ReviewDetails.spec.tsx b/__tests__/ReviewDetails.spec.tsxindex 6f2c233..dbcbb64 100644--- a/__tests__/ReviewDetails.spec.tsx+++ b/__tests__/ReviewDetails.spec.tsx@@ -33,8 +33,22 @@ describe("ReviewDetails", () => {expect(screen.getByText("Impact 80 · Clarity 82 · ATS 78"),).toBeInTheDocument();- const expected = `Reviewed on ${format(new Date(reviewData.reviewedAt!), "MMM d, yyyy 'at' h:mm a")} using openai / gpt-4o`;- expect(screen.getByText(/Reviewed on/)).toHaveTextContent(expected);+ const date = format(+ new Date(reviewData.reviewedAt!),+ "MMM d, yyyy 'at' h:mm a",+ );+ expect(screen.getByText(`Reviewed on ${date}`)).toBeInTheDocument();+ expect(screen.getByText("using openai / gpt-4o")).toBeInTheDocument();+ });++ it("shows a 'via <agent>' badge for an MCP-sourced review instead of the provider text", () => {+ render(+ <ReviewDetails+ reviewData={{ ...reviewData, provider: "mcp", model: "my-agent-token" }}+ />,+ );+ expect(screen.getByText(/via my-agent-token/)).toBeInTheDocument();+ expect(screen.queryByText(/using/)).not.toBeInTheDocument();});it("hides the full markdown body by default", () => {diff --git a/__tests__/mcpReviewResume.spec.ts b/__tests__/mcpReviewResume.spec.tsnew file mode 100644index 0000000..8b325a9--- /dev/null+++ b/__tests__/mcpReviewResume.spec.ts@@ -0,0 +1,99 @@+import { handleReviewResume } from "@/lib/mcp/tools/reviewResume";+import { getDefaultResumeForUser } from "@/lib/jobs/getDefaultResumeForUser";+import { preprocessResume } from "@/lib/ai/tools/preprocessing";+import { checkMcpRateLimit } from "@/lib/mcp/rate-limit";+import { APP_CONSTANTS } from "@/lib/constants";++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 longResumeText = "a".repeat(APP_CONSTANTS.MCP_REVIEW_MIN_RESUME_LENGTH);+const shortResumeText = "too short";++describe("handleReviewResume", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("returns a directive containing resume text + resumeId + save instruction on the happy path", async () => {+ (getDefaultResumeForUser as any).mockResolvedValue({ id: "resume-1" });+ (preprocessResume as any).mockResolvedValue({+ success: true,+ data: { normalizedText: longResumeText, metadata: {}, isValid: true },+ });++ const result = await handleReviewResume("user-1");+ const text = result.content[0].text;++ expect(text).toContain(longResumeText);+ expect(text).toContain("resume-1");+ expect(text).toContain("save_resume_review");+ expect(text).toContain(+ "SCORES: overall=<0-100> impact=<0-100> clarity=<0-100> ats=<0-100>",+ );+ expect(text).toContain('"resumeId": "resume-1"');+ });++ it("returns a note when no default resume is set", async () => {+ (getDefaultResumeForUser as any).mockResolvedValue(null);++ const result = await handleReviewResume("user-2");+ const text = result.content[0].text;++ expect(text).toContain("No default resume set");+ expect(text).not.toContain("save_resume_review");+ expect(preprocessResume).not.toHaveBeenCalled();+ });++ it("returns a distinct note when preprocessing fails", async () => {+ (getDefaultResumeForUser as any).mockResolvedValue({ id: "resume-1" });+ (preprocessResume as any).mockResolvedValue({+ success: false,+ error: { code: "TOO_SHORT", message: "Resume is too short" },+ });++ const result = await handleReviewResume("user-3");+ const text = result.content[0].text;++ expect(text).toContain("couldn't be used for review");+ expect(text).not.toContain("No default resume set");+ expect(text).not.toContain("save_resume_review");+ });++ it("returns a too-short note when normalized text is under the length threshold", async () => {+ (getDefaultResumeForUser as any).mockResolvedValue({ id: "resume-1" });+ (preprocessResume as any).mockResolvedValue({+ success: true,+ data: { normalizedText: shortResumeText, metadata: {}, isValid: true },+ });++ const result = await handleReviewResume("user-4");+ const text = result.content[0].text;++ expect(text).toBe("Resume too short to review.");+ expect(text).not.toContain("save_resume_review");+ });++ it("returns a rate-limit message and never loads a resume when the limit is exceeded", async () => {+ (checkMcpRateLimit as any).mockReturnValueOnce({+ allowed: false,+ resetIn: 60000,+ });++ const result = await handleReviewResume("user-5");+ const text = result.content[0].text;++ expect(text).toContain("Rate limit exceeded");+ expect(text).toContain("60s");+ expect(getDefaultResumeForUser).not.toHaveBeenCalled();+ });+});diff --git a/__tests__/mcpSaveResumeReview.spec.ts b/__tests__/mcpSaveResumeReview.spec.tsnew file mode 100644index 0000000..8e1e9d0--- /dev/null+++ b/__tests__/mcpSaveResumeReview.spec.ts@@ -0,0 +1,147 @@+import { handleSaveResumeReview } from "@/lib/mcp/tools/saveResumeReview";+import { checkMcpRateLimit } from "@/lib/mcp/rate-limit";+import { PrismaClient } from "@prisma/client";++const prisma = new PrismaClient();++vi.mock("@prisma/client", () => {+ const mPrismaClient = {+ resume: { update: vi.fn() },+ };+ return { PrismaClient: vi.fn(function () { return mPrismaClient; }) };+});++vi.mock("@/lib/mcp/rate-limit", () => ({+ checkMcpRateLimit: vi.fn(() => ({ allowed: true, resetIn: 0 })),+}));++const validReviewText =+ "SCORES: overall=80 impact=70 clarity=90 ats=60\n\n## Summary\nSolid resume.";++describe("handleSaveResumeReview", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ (prisma.resume.update as any).mockResolvedValue({ id: "resume-1" });+ });++ it("parses a valid reviewText and persists the shaped ResumeReviewData (overwrite)", async () => {+ const result = await handleSaveResumeReview(+ { resumeId: "resume-1", reviewText: validReviewText },+ "user-1",+ "my-token",+ );++ expect(prisma.resume.update).toHaveBeenCalledWith({+ where: { id: "resume-1", profile: { userId: "user-1" } },+ data: { reviewData: expect.any(String) },+ });++ const call = (prisma.resume.update as any).mock.calls[0][0];+ const reviewData = JSON.parse(call.data.reviewData);+ expect(reviewData).toMatchObject({+ overall: 80,+ impact: 70,+ clarity: 90,+ atsCompatibility: 60,+ provider: "mcp",+ model: "my-token",+ });+ expect(reviewData.body).toContain("Solid resume.");+ expect(typeof reviewData.reviewedAt).toBe("string");++ expect(result.content[0].text).toContain("Review saved for resume resume-1");+ expect(result.content[0].text).toContain("80");+ });++ it("returns a parse-error message when reviewText has no SCORES line", async () => {+ const result = await handleSaveResumeReview(+ { resumeId: "resume-1", reviewText: "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.resume.update).not.toHaveBeenCalled();+ });++ it("returns a not-found message on P2025 (unowned or missing resumeId)", async () => {+ (prisma.resume.update as any).mockRejectedValue({ code: "P2025" });++ const result = await handleSaveResumeReview(+ { resumeId: "someone-elses-resume", reviewText: validReviewText },+ "user-3",+ "my-token",+ );++ expect(result.content[0].text).toBe(+ "Resume not found or not owned by this token's user.",+ );+ });++ it("overwrites a prior review (last-write-wins, no pre-check)", async () => {+ await handleSaveResumeReview(+ { resumeId: "resume-1", reviewText: validReviewText },+ "user-4",+ "my-token",+ );+ await handleSaveResumeReview(+ {+ resumeId: "resume-1",+ reviewText:+ "SCORES: overall=40 impact=30 clarity=50 ats=20\n\nUpdated review.",+ },+ "user-4",+ "my-token",+ );++ expect(prisma.resume.update).toHaveBeenCalledTimes(2);+ const secondCall = (prisma.resume.update as any).mock.calls[1][0];+ const reviewData = JSON.parse(secondCall.data.reviewData);+ expect(reviewData.overall).toBe(40);+ });++ 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 handleSaveResumeReview(+ { resumeId: "resume-1", reviewText: validReviewText },+ "user-5",+ "my-token",+ );++ expect(result.content[0].text).toContain("Rate limit exceeded");+ expect(prisma.resume.update).not.toHaveBeenCalled();+ });++ it("clamps out-of-range scores into 0-100", async () => {+ await handleSaveResumeReview(+ {+ resumeId: "resume-1",+ reviewText:+ "SCORES: overall=1000 impact=0 clarity=50 ats=999\n\nOverqualified.",+ },+ "user-6",+ "my-token",+ );++ const call = (prisma.resume.update as any).mock.calls[0][0];+ const reviewData = JSON.parse(call.data.reviewData);+ expect(reviewData.overall).toBe(100);+ expect(reviewData.atsCompatibility).toBe(100);+ });++ it("surfaces a generic error message on a non-P2025 DB failure", async () => {+ (prisma.resume.update as any).mockRejectedValue({ message: "connection reset" });++ const result = await handleSaveResumeReview(+ { resumeId: "resume-1", reviewText: validReviewText },+ "user-7",+ "my-token",+ );++ expect(result.content[0].text).toContain("Error: connection reset");+ });+});diff --git a/__tests__/resumeReviewParse.spec.ts b/__tests__/resumeReviewParse.spec.tsnew file mode 100644index 0000000..a8422c3--- /dev/null+++ b/__tests__/resumeReviewParse.spec.ts@@ -0,0 +1,58 @@+import { parseResumeReview } from "@/lib/ai/resumeReview/parse";++describe("parseResumeReview", () => {+ it("parses a valid SCORES line and strips it from the body", () => {+ const raw =+ "SCORES: overall=80 impact=70 clarity=90 ats=60\n\n## Summary\nGood resume.";+ const result = parseResumeReview(raw);++ expect(result.scores).toEqual({+ overall: 80,+ impact: 70,+ clarity: 90,+ atsCompatibility: 60,+ });+ expect(result.body).toBe("## Summary\nGood resume.");+ });++ it("clamps out-of-range values into 0-100", () => {+ const raw = "SCORES: overall=1000 impact=0 clarity=50 ats=999\n\nBody.";+ const result = parseResumeReview(raw);++ expect(result.scores).toEqual({+ overall: 100,+ impact: 0,+ clarity: 50,+ atsCompatibility: 100,+ });+ });++ it("returns no scores when the SCORES line is missing, and strips a leading partial line", () => {+ const raw = "SCORES: overall=5\n\nJust some body text.";+ const result = parseResumeReview(raw);++ expect(result.scores).toBeUndefined();+ expect(result.body).toBe("Just some body text.");+ });++ it("strips <think> blocks before parsing", () => {+ const raw =+ "<think>reasoning about the resume</think>SCORES: overall=80 impact=70 clarity=90 ats=60\n\n## Summary\nGood resume.";+ const result = parseResumeReview(raw);++ expect(result.scores).toEqual({+ overall: 80,+ impact: 70,+ clarity: 90,+ atsCompatibility: 60,+ });+ expect(result.body).toBe("## Summary\nGood resume.");+ });++ it("trims leading whitespace from the body", () => {+ const raw = "SCORES: overall=80 impact=70 clarity=90 ats=60\n\n\n ## Summary";+ const result = parseResumeReview(raw);++ expect(result.body).toBe("## Summary");+ });+});diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 7773fed..d3dcbb4 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -510,7 +510,7 @@ model McpAccessToken {name StringtokenHash String @uniquetokenPrefix String- scopes String // JSON array string; new tokens are always ["jobs:write","questions:write"]+ scopes String // JSON array string; new tokens are always ["jobs:write","questions:write","resume:write"]expiresAt DateTimelastUsedAt DateTime?createdAt DateTime @default(now())diff --git a/src/actions/mcpToken.actions.ts b/src/actions/mcpToken.actions.tsindex 7dd99d6..c3af178 100644--- a/src/actions/mcpToken.actions.ts+++ b/src/actions/mcpToken.actions.ts@@ -44,7 +44,7 @@ export async function createMcpToken(input: {name: input.name.trim(),tokenHash: hash,tokenPrefix: prefix,- scopes: JSON.stringify(["jobs:write", "questions:write"]),+ scopes: JSON.stringify(["jobs:write", "questions:write", "resume:write"]),expiresAt,},});diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.tsindex 5d6202a..b483de4 100644--- a/src/app/api/mcp/route.ts+++ b/src/app/api/mcp/route.ts@@ -8,10 +8,16 @@ import {McpAddQuestionSchema,McpSaveMatchResultInputShape,McpSaveMatchResultSchema,+ McpReviewResumeInputShape,+ McpReviewResumeSchema,+ McpSaveResumeReviewInputShape,+ McpSaveResumeReviewSchema,} 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";function isMcpEnabled(): boolean {const env = process.env.MCP_ENABLED;@@ -122,6 +128,38 @@ async function handler(req: Request): Promise<Response> {},);+ // 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 (see+ // docs/plans/feature-mcp-resume-review.md, "Locked decisions"). Do not add+ // one without also backfilling existing tokens.+ server.tool(+ "review_resume",+ "Fetch the user's default resume so you can review it. Returns the normalized resume text plus a directive — produce the review yourself, then call save_resume_review with the result.",+ McpReviewResumeInputShape,+ async () => {+ return handleReviewResume(userId);+ },+ );++ server.tool(+ "save_resume_review",+ "Persist a resume review (produced by you, the agent) against the resume previously handed to you by review_resume. Call this after review_resume hands you a review directive.",+ McpSaveResumeReviewInputShape,+ async (rawInput) => {+ const parsed = McpSaveResumeReviewSchema.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 handleSaveResumeReview(parsed.data, userId, tokenName);+ },+ );+const transport = new WebStandardStreamableHTTPServerTransport({sessionIdGenerator: undefined, // stateless modeenableJsonResponse: true, // return plain JSON instead of SSE streamdiff --git a/src/components/profile/ReviewDetails.tsx b/src/components/profile/ReviewDetails.tsxindex a46c1f1..9a8a740 100644--- a/src/components/profile/ReviewDetails.tsx+++ b/src/components/profile/ReviewDetails.tsx@@ -3,8 +3,9 @@import { useMemo, useState } from "react";import MarkdownIt from "markdown-it";import { format } from "date-fns";-import { ChevronDown } from "lucide-react";+import { ChevronDown, Sparkles } from "lucide-react";import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";import {Collapsible,CollapsibleContent,@@ -42,14 +43,27 @@ export function ReviewDetails({ reviewData }: ReviewDetailsProps) {{reviewData.atsCompatibility}</span></div>- <p className="text-xs text-muted-foreground">- {reviewData.reviewedAt- ? `Reviewed on ${format(new Date(reviewData.reviewedAt), "MMM d, yyyy 'at' h:mm a")}`- : null}- {reviewData.provider- ? ` using ${reviewData.provider}${reviewData.model ? ` / ${reviewData.model}` : ""}`- : null}- </p>+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">+ {reviewData.reviewedAt ? (+ <span>+ Reviewed on{" "}+ {format(+ new Date(reviewData.reviewedAt),+ "MMM d, yyyy 'at' h:mm a",+ )}+ </span>+ ) : null}+ {reviewData.provider === "mcp"+ ? reviewData.model && (+ <Badge className="gap-1 bg-violet-500 dark:bg-violet-400">+ <Sparkles className="h-3.5 w-3.5" />+ via {reviewData.model}+ </Badge>+ )+ : reviewData.provider+ ? `using ${reviewData.provider}${reviewData.model ? ` / ${reviewData.model}` : ""}`+ : null}+ </div></div><CollapsibleTrigger asChild>diff --git a/src/lib/ai/resumeReview/parse.ts b/src/lib/ai/resumeReview/parse.tsnew file mode 100644index 0000000..b3a71a5--- /dev/null+++ b/src/lib/ai/resumeReview/parse.ts@@ -0,0 +1,42 @@+import type { ResumeScores } from "@/models/ai.schemas";+import { stripThinking } from "@/lib/ai/stripThinking";++// Isomorphic parser shared by the client stream util and the MCP save+// handler. No `server-only`, no `fetch` — pure text -> result.++export type ResumeReviewResult = {+ scores?: ResumeScores;+ // Markdown review body (scores line and any <think> blocks stripped out).+ body: string;+};++// Match greedily on digits (not {1,3}) so an out-of-range value like 1000+// still parses — clamp() below brings it back into 0-100 rather than failing+// the whole line and dropping every score.+const SCORES_RE =+ /SCORES:\s*overall=(\d+)\s+impact=(\d+)\s+clarity=(\d+)\s+ats=(\d+)/i;++export function parseResumeReview(raw: string): ResumeReviewResult {+ const text = stripThinking(raw);+ const match = text.match(SCORES_RE);++ let scores: ResumeScores | undefined;+ if (match) {+ const clamp = (n: number) => Math.max(0, Math.min(100, n));+ scores = {+ overall: clamp(Number(match[1])),+ impact: clamp(Number(match[2])),+ clarity: clamp(Number(match[3])),+ atsCompatibility: clamp(Number(match[4])),+ };+ }++ // Remove the scores line from the body. Before it has fully streamed, also+ // hide a leading partial "SCORES:" line so it doesn't flash in the markdown.+ let body = match+ ? text.replace(match[0], "")+ : text.replace(/^\s*SCORES:[^\n]*(\n|$)/i, "");+ body = body.replace(/^\s+/, "");++ return { scores, body };+}diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex 7592c1d..a168c6f 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -98,6 +98,7 @@ export const APP_CONSTANTS = {MCP_DEFAULT_STATUS: "draft",MCP_MATCH_MIN_DESCRIPTION_LENGTH: 200,MCP_MATCH_PROVIDER_MARKER: "mcp",+ MCP_REVIEW_MIN_RESUME_LENGTH: 400,// File uploadsUPLOADS_DIR: process.env.NODE_ENV !== "production" ? "data" : "/data",diff --git a/src/lib/mcp/tools/addJob.ts b/src/lib/mcp/tools/addJob.tsindex 517c715..3c072ee 100644--- a/src/lib/mcp/tools/addJob.ts+++ b/src/lib/mcp/tools/addJob.ts@@ -6,13 +6,6 @@ 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",- description:- "Add a job application to JobSync. Resolves or creates company, job title, location, and source by name. Returns a transparency report of what was matched vs. created.",- inputSchema: McpAddJobSchema,-} as const;-function buildMatchDirective(jobId: string,resumeId: string,diff --git a/src/lib/mcp/tools/addQuestion.ts b/src/lib/mcp/tools/addQuestion.tsindex c010913..553f901 100644--- a/src/lib/mcp/tools/addQuestion.ts+++ b/src/lib/mcp/tools/addQuestion.ts@@ -3,13 +3,6 @@ import { McpAddQuestionSchema } from "@/models/mcp.schema";import { createQuestionFromNames } from "@/lib/questions/createQuestionFromNames";import { checkMcpRateLimit } from "@/lib/mcp/rate-limit";-export const addQuestionToolDefinition = {- name: "add_question",- description:- "Add an entry to the Question Bank. Resolves or creates tags by name. Returns a transparency report of what was matched vs. created.",- inputSchema: McpAddQuestionSchema,-} as const;-export async function handleAddQuestion(input: z.infer<typeof McpAddQuestionSchema>,userId: string,diff --git a/src/lib/mcp/tools/reviewResume.ts b/src/lib/mcp/tools/reviewResume.tsnew file mode 100644index 0000000..780af95--- /dev/null+++ b/src/lib/mcp/tools/reviewResume.ts@@ -0,0 +1,72 @@+import { APP_CONSTANTS } from "@/lib/constants";+import { checkMcpRateLimit } from "@/lib/mcp/rate-limit";+import { getDefaultResumeForUser } from "@/lib/jobs/getDefaultResumeForUser";+import { preprocessResume } from "@/lib/ai/tools/preprocessing";+import { RESUME_REVIEW_SYSTEM_PROMPT } from "@/lib/ai/prompts/resume-review";++// Do not restate the SCORES line format or the "##" section list here —+// RESUME_REVIEW_SYSTEM_PROMPT already fully specifies both. Restating them+// would create two sources that can drift.+function buildReviewDirective(+ resumeId: string,+ normalizedResumeText: string,+): string {+ return (+ `Act as the reviewer described below and produce a review of the ` ++ `resume shown here.\n\n` ++ `DEFAULT RESUME (normalized):\n${normalizedResumeText}\n\n` ++ `${RESUME_REVIEW_SYSTEM_PROMPT}\n\n` ++ `Then call save_resume_review with the full SCORES line + markdown body ` ++ `you just produced as the "reviewText" argument (not as a chat message):\n` ++ ` { "resumeId": "${resumeId}", "reviewText": "<the full SCORES line + markdown body>" }`+ );+}++export async function handleReviewResume(+ 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.` },+ ],+ };+ }++ const resume = await getDefaultResumeForUser(userId);+ if (!resume) {+ return {+ content: [+ {+ type: "text",+ text: "No default resume set — set one in Profile → Resumes.",+ },+ ],+ };+ }++ const pre = await preprocessResume(resume);+ if (!pre.success) {+ return {+ content: [+ {+ type: "text",+ text: "Default resume couldn't be used for review (it may be too short or missing content) — check it in Profile → Resumes.",+ },+ ],+ };+ }++ if (+ pre.data.normalizedText.length < APP_CONSTANTS.MCP_REVIEW_MIN_RESUME_LENGTH+ ) {+ return {+ content: [{ type: "text", text: "Resume too short to review." }],+ };+ }++ const directive = buildReviewDirective(resume.id!, pre.data.normalizedText);+ return { content: [{ type: "text", text: directive }] };+}diff --git a/src/lib/mcp/tools/saveMatchResult.ts b/src/lib/mcp/tools/saveMatchResult.tsindex c2ee247..69f2027 100644--- a/src/lib/mcp/tools/saveMatchResult.ts+++ b/src/lib/mcp/tools/saveMatchResult.ts@@ -6,13 +6,6 @@ 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,diff --git a/src/lib/mcp/tools/saveResumeReview.ts b/src/lib/mcp/tools/saveResumeReview.tsnew file mode 100644index 0000000..48b4ea8--- /dev/null+++ b/src/lib/mcp/tools/saveResumeReview.ts@@ -0,0 +1,85 @@+import { z } from "zod";+import prisma from "@/lib/db";+import { APP_CONSTANTS } from "@/lib/constants";+import { McpSaveResumeReviewSchema } from "@/models/mcp.schema";+import { checkMcpRateLimit } from "@/lib/mcp/rate-limit";+import { parseResumeReview } from "@/lib/ai/resumeReview/parse";+import type { ResumeReviewData } from "@/models/ai.schemas";++export async function handleSaveResumeReview(+ input: z.infer<typeof McpSaveResumeReviewSchema>,+ userId: string,+ tokenName: string,+): Promise<{ content: Array<{ type: "text"; text: string }> }> {+ // Shares review_resume's bucket by design. At the exact window boundary a+ // review can be computed but rejected here; accepted — the user can retry+ // or review 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 = parseResumeReview(input.reviewText);+ if (!parsed.scores) {+ return {+ content: [+ {+ type: "text",+ text:+ "Could not parse a SCORES line. Include a leading 'SCORES: " ++ "overall=<0-100> impact=<0-100> clarity=<0-100> ats=<0-100>' line.",+ },+ ],+ };+ }++ const reviewData: ResumeReviewData = {+ overall: parsed.scores.overall,+ impact: parsed.scores.impact,+ clarity: parsed.scores.clarity,+ atsCompatibility: parsed.scores.atsCompatibility,+ body: parsed.body,+ reviewedAt: new Date().toISOString(),+ provider: APP_CONSTANTS.MCP_MATCH_PROVIDER_MARKER,+ model: tokenName,+ };++ // No separate ownership findFirst — the update `where` already enforces+ // ownership and throws P2025 when the resume isn't the user's or no longer+ // exists (unlike saveMatchResult's findFirst, which earns its keep by+ // fetching `title` for provenance; ResumeReviewData has no such field).+ try {+ await prisma.resume.update({+ where: { id: input.resumeId, profile: { userId } },+ data: { reviewData: JSON.stringify(reviewData) },+ });+ } catch (error: any) {+ if (error?.code === "P2025") {+ return {+ content: [+ {+ type: "text",+ text: "Resume not found or not owned by this token's user.",+ },+ ],+ };+ }+ return {+ content: [{ type: "text", text: `Error: ${error?.message ?? "Unknown error"}` }],+ };+ }++ return {+ content: [+ {+ type: "text",+ text: `Review saved for resume ${input.resumeId} (overall score ${parsed.scores.overall}).`,+ },+ ],+ };+}diff --git a/src/models/mcp.schema.ts b/src/models/mcp.schema.tsindex 4c50d85..8bca74a 100644--- a/src/models/mcp.schema.ts+++ b/src/models/mcp.schema.ts@@ -65,3 +65,31 @@ export const McpSaveMatchResultInputShape = {export const McpSaveMatchResultSchema = z.object(McpSaveMatchResultInputShape);export type McpSaveMatchResultInput = z.infer<typeof McpSaveMatchResultSchema>;++// No arguments — always reviews the caller's default resume.+export const McpReviewResumeInputShape = {};++export const McpReviewResumeSchema = z.object(McpReviewResumeInputShape);+export type McpReviewResumeInput = z.infer<typeof McpReviewResumeSchema>;++// Raw input shape for MCP tool registration (no transforms needed)+export const McpSaveResumeReviewInputShape = {+ resumeId: z+ .string()+ .min(1)+ .describe(+ "The id of the resume this review was produced for, exactly as given " ++ "in the review_resume directive.",+ ),+ reviewText: z.string().min(20).describe(+ "Your full resume review: a leading 'SCORES: overall=<0-100> " ++ "impact=<0-100> clarity=<0-100> ats=<0-100>' line, then a markdown body.",+ ),+};++export const McpSaveResumeReviewSchema = z.object(+ McpSaveResumeReviewInputShape,+);+export type McpSaveResumeReviewInput = z.infer<+ typeof McpSaveResumeReviewSchema+>;diff --git a/src/utils/streamResumeReview.utils.ts b/src/utils/streamResumeReview.utils.tsindex d9e30c0..f00021a 100644--- a/src/utils/streamResumeReview.utils.ts+++ b/src/utils/streamResumeReview.utils.ts@@ -1,12 +1,10 @@-import { ResumeScores } from "@/models/ai.schemas";import { AiModel } from "@/models/ai.model";-import { stripThinking } from "@/lib/ai/stripThinking";+import {+ parseResumeReview,+ type ResumeReviewResult,+} from "@/lib/ai/resumeReview/parse";-export type ResumeReviewResult = {- scores?: ResumeScores;- // Markdown review body (scores line and any <think> blocks stripped out).- body: string;-};+export type { ResumeReviewResult } from "@/lib/ai/resumeReview/parse";type StreamResumeReviewArgs = {resumeId: string;@@ -16,37 +14,6 @@ type StreamResumeReviewArgs = {signal?: AbortSignal;};-// Match greedily on digits (not {1,3}) so an out-of-range value like 1000-// still parses — clamp() below brings it back into 0-100 rather than failing-// the whole line and dropping every score.-const SCORES_RE =- /SCORES:\s*overall=(\d+)\s+impact=(\d+)\s+clarity=(\d+)\s+ats=(\d+)/i;--function parse(raw: string): ResumeReviewResult {- const text = stripThinking(raw);- const match = text.match(SCORES_RE);-- let scores: ResumeScores | undefined;- if (match) {- const clamp = (n: number) => Math.max(0, Math.min(100, n));- scores = {- overall: clamp(Number(match[1])),- impact: clamp(Number(match[2])),- clarity: clamp(Number(match[3])),- atsCompatibility: clamp(Number(match[4])),- };- }-- // Remove the scores line from the body. Before it has fully streamed, also- // hide a leading partial "SCORES:" line so it doesn't flash in the markdown.- let body = match- ? text.replace(match[0], "")- : text.replace(/^\s*SCORES:[^\n]*(\n|$)/i, "");- body = body.replace(/^\s+/, "");-- return { scores, body };-}-// Consumes the plain-text stream from /api/ai/resume/review and returns the// parsed scores + markdown body. Salvages whatever arrived if the stream ends// abnormally.@@ -84,14 +51,14 @@ export async function streamResumeReview({const { done, value } = await reader.read();if (done) break;raw += decoder.decode(value, { stream: true });- onUpdate?.(parse(raw));+ onUpdate?.(parseResumeReview(raw));}} catch (err) {// Abnormal end (abort / incomplete chunked encoding): keep what we have.if (!raw) throw err;}- const final = parse(raw);+ const final = parseResumeReview(raw);if (!final.body && !final.scores) {throw new Error("The AI service returned no data. Please ensure it is running and try again.",