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 support - Add job tool call
Khuram Niaz2639c111320b
diff --git a/__tests__/tag.actions.spec.ts b/__tests__/tag.actions.spec.tsindex e9dc376..223ab38 100644--- a/__tests__/tag.actions.spec.ts+++ b/__tests__/tag.actions.spec.ts@@ -14,7 +14,8 @@ vi.mock("@prisma/client", () => {tag: {findMany: vi.fn(),count: vi.fn(),- upsert: vi.fn(),+ findUnique: vi.fn(),+ create: vi.fn(),delete: vi.fn(),},job: {@@ -141,29 +142,32 @@ describe("Tag Actions", () => {// createTagdescribe("createTag", () => {- it("should upsert and return the tag on success", async () => {+ it("should create and return the tag on success", async () => {(getCurrentUser as any).mockResolvedValue(mockUser);- (prisma.tag.upsert as any).mockResolvedValue(mockTag);+ (prisma.tag.findUnique as any).mockResolvedValue(null);+ (prisma.tag.create as any).mockResolvedValue(mockTag);const result = await createTag("React");expect(result).toEqual({ data: mockTag, success: true });- expect(prisma.tag.upsert).toHaveBeenCalledWith({+ expect(prisma.tag.findUnique).toHaveBeenCalledWith({where: { value_createdBy: { value: "react", createdBy: mockUser.id } },- update: {},- create: { label: "React", value: "react", createdBy: mockUser.id },+ });+ expect(prisma.tag.create).toHaveBeenCalledWith({+ data: { label: "React", value: "react", createdBy: mockUser.id },});});it("should trim label and lowercase the value", async () => {(getCurrentUser as any).mockResolvedValue(mockUser);- (prisma.tag.upsert as any).mockResolvedValue(mockTag);+ (prisma.tag.findUnique as any).mockResolvedValue(null);+ (prisma.tag.create as any).mockResolvedValue(mockTag);await createTag(" React ");- expect(prisma.tag.upsert).toHaveBeenCalledWith(+ expect(prisma.tag.create).toHaveBeenCalledWith(expect.objectContaining({- create: expect.objectContaining({ label: "React", value: "react" }),+ data: expect.objectContaining({ label: "React", value: "react" }),}),);});@@ -177,7 +181,8 @@ describe("Tag Actions", () => {success: false,message: "Tag label cannot be empty.",});- expect(prisma.tag.upsert).not.toHaveBeenCalled();+ expect(prisma.tag.findUnique).not.toHaveBeenCalled();+ expect(prisma.tag.create).not.toHaveBeenCalled();});it("should return error for unauthenticated user", async () => {@@ -186,12 +191,14 @@ describe("Tag Actions", () => {const result = await createTag("React");expect(result).toEqual({ success: false, message: "Not authenticated" });- expect(prisma.tag.upsert).not.toHaveBeenCalled();+ expect(prisma.tag.findUnique).not.toHaveBeenCalled();+ expect(prisma.tag.create).not.toHaveBeenCalled();});it("should handle database errors", async () => {(getCurrentUser as any).mockResolvedValue(mockUser);- (prisma.tag.upsert as any).mockRejectedValue(new Error("DB error"));+ (prisma.tag.findUnique as any).mockResolvedValue(null);+ (prisma.tag.create as any).mockRejectedValue(new Error("DB error"));const result = await createTag("React");diff --git a/package-lock.json b/package-lock.jsonindex df14304..bc229d3 100644--- a/package-lock.json+++ b/package-lock.json@@ -13,6 +13,7 @@"@ai-sdk/openai": "^3.0.2","@ai-sdk/react": "^3.0.5","@hookform/resolvers": "^5.2.2",+ "@modelcontextprotocol/sdk": "^1.26.0","@nivo/bar": "^0.99.0","@nivo/calendar": "^0.99.0","@nivo/core": "^0.99.0",@@ -50,6 +51,7 @@"lucide-react": "^0.469.0","mammoth": "^1.12.0","markdown-it": "^14.1.0",+ "mcp-handler": "^1.1.0","next": "^15.5.18","next-auth": "^5.0.0-beta.30","next-themes": "^0.4.4",@@ -3146,9 +3148,7 @@"version": "1.19.14","resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz","integrity": "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==",- "dev": true,"license": "MIT",- "optional": true,"engines": {"node": ">=18.14.1"},@@ -4127,12 +4127,12 @@"license": "MIT"},"node_modules/@modelcontextprotocol/sdk": {- "version": "1.22.0",- "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.22.0.tgz",- "integrity": "sha512-VUpl106XVTCpDmTBil2ehgJZjhyLY2QZikzF8NvTXtLRF1CvO5iEE2UNZdVIUer35vFOwMKYeUGbjJtvPWan3g==",- "dev": true,+ "version": "1.26.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.26.0.tgz",+ "integrity": "sha512-Y5RmPncpiDtTXDbLKswIJzTqu2hyBKxTNsgKqKclDbhIgg1wgtf1fRuvxgTnRfcnxtvvgbIEcqUOzZrJ6iSReg==","license": "MIT","dependencies": {+ "@hono/node-server": "^1.19.9","ajv": "^8.17.1","ajv-formats": "^3.0.1","content-type": "^1.0.5",@@ -4140,22 +4140,29 @@"cross-spawn": "^7.0.5","eventsource": "^3.0.2","eventsource-parser": "^3.0.0",- "express": "^5.0.1",- "express-rate-limit": "^7.5.0",+ "express": "^5.2.1",+ "express-rate-limit": "^8.2.1",+ "hono": "^4.11.4",+ "jose": "^6.1.3",+ "json-schema-typed": "^8.0.2","pkce-challenge": "^5.0.0","raw-body": "^3.0.0",- "zod": "^3.23.8",- "zod-to-json-schema": "^3.24.1"+ "zod": "^3.25 || ^4.0",+ "zod-to-json-schema": "^3.25.1"},"engines": {"node": ">=18"},"peerDependencies": {- "@cfworker/json-schema": "^4.1.1"+ "@cfworker/json-schema": "^4.1.1",+ "zod": "^3.25 || ^4.0"},"peerDependenciesMeta": {"@cfworker/json-schema": {"optional": true+ },+ "zod": {+ "optional": false}}},@@ -4163,7 +4170,6 @@"version": "8.20.0","resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz","integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",- "dev": true,"license": "MIT","dependencies": {"fast-deep-equal": "^3.1.3",@@ -4180,19 +4186,8 @@"version": "1.0.0","resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz","integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",- "dev": true,"license": "MIT"},- "node_modules/@modelcontextprotocol/sdk/node_modules/zod": {- "version": "3.25.76",- "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",- "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",- "dev": true,- "license": "MIT",- "funding": {- "url": "https://github.com/sponsors/colinhacks"- }- },"node_modules/@mongodb-js/saslprep": {"version": "1.4.11","resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.4.11.tgz",@@ -4780,26 +4775,6 @@"url": "https://github.com/sponsors/epoberezkin"}},- "node_modules/@openai/agents-core/node_modules/express-rate-limit": {- "version": "8.5.2",- "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.2.tgz",- "integrity": "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==",- "dev": true,- "license": "MIT",- "optional": true,- "dependencies": {- "ip-address": "^10.2.0"- },- "engines": {- "node": ">= 16"- },- "funding": {- "url": "https://github.com/sponsors/express-rate-limit"- },- "peerDependencies": {- "express": ">= 4.11"- }- },"node_modules/@openai/agents-core/node_modules/json-schema-traverse": {"version": "1.0.0","resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",@@ -9154,7 +9129,6 @@"version": "2.0.0","resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz","integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",- "dev": true,"license": "MIT","dependencies": {"mime-types": "^3.0.0",@@ -9168,7 +9142,6 @@"version": "1.0.0","resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz","integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.6"@@ -9283,7 +9256,6 @@"version": "3.0.1","resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz","integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",- "dev": true,"license": "MIT","dependencies": {"ajv": "^8.0.0"@@ -9301,7 +9273,6 @@"version": "8.20.0","resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz","integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",- "dev": true,"license": "MIT","dependencies": {"fast-deep-equal": "^3.1.3",@@ -9318,7 +9289,6 @@"version": "1.0.0","resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz","integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",- "dev": true,"license": "MIT"},"node_modules/ansi-regex": {@@ -9915,7 +9885,6 @@"version": "2.2.2","resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz","integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==",- "dev": true,"license": "MIT","dependencies": {"bytes": "^3.1.2",@@ -9940,7 +9909,6 @@"version": "0.7.2","resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz","integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",- "dev": true,"license": "MIT","dependencies": {"safer-buffer": ">= 2.1.2 < 3.0.0"@@ -10068,7 +10036,6 @@"version": "3.1.2","resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz","integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.8"@@ -10168,7 +10135,6 @@"version": "1.0.2","resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz","integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",- "dev": true,"license": "MIT","dependencies": {"es-errors": "^1.3.0",@@ -10182,7 +10148,6 @@"version": "1.0.4","resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz","integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",- "dev": true,"license": "MIT","dependencies": {"call-bind-apply-helpers": "^1.0.2",@@ -10464,9 +10429,7 @@"version": "1.1.2","resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz","integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==",- "dev": true,"license": "Apache-2.0",- "optional": true,"engines": {"node": ">=0.10.0"}@@ -10680,7 +10643,6 @@"version": "1.1.0","resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz","integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",- "dev": true,"license": "MIT","engines": {"node": ">=18"@@ -10694,7 +10656,6 @@"version": "1.0.5","resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz","integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.6"@@ -10711,7 +10672,6 @@"version": "0.7.2","resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz","integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.6"@@ -10721,7 +10681,6 @@"version": "1.2.2","resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz","integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",- "dev": true,"license": "MIT","engines": {"node": ">=6.6.0"@@ -10737,7 +10696,6 @@"version": "2.8.6","resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz","integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",- "dev": true,"license": "MIT","dependencies": {"object-assign": "^4",@@ -10779,7 +10737,6 @@"version": "7.0.6","resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz","integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",- "dev": true,"license": "MIT","dependencies": {"path-key": "^3.1.0",@@ -11096,7 +11053,6 @@"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz","integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",- "dev": true,"license": "MIT","dependencies": {"ms": "^2.1.3"@@ -11328,7 +11284,6 @@"version": "2.0.0","resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz","integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.8"@@ -11572,7 +11527,6 @@"version": "1.0.1","resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz","integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",- "dev": true,"license": "MIT","dependencies": {"call-bind-apply-helpers": "^1.0.1",@@ -11676,7 +11630,6 @@"version": "1.1.1","resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz","integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",- "dev": true,"license": "MIT"},"node_modules/effect": {@@ -11724,7 +11677,6 @@"version": "2.0.0","resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz","integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.8"@@ -11933,7 +11885,6 @@"version": "1.0.1","resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz","integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.4"@@ -11943,7 +11894,6 @@"version": "1.3.0","resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz","integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.4"@@ -11989,7 +11939,6 @@"version": "1.1.1","resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz","integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",- "dev": true,"license": "MIT","dependencies": {"es-errors": "^1.3.0"@@ -12101,7 +12050,6 @@"version": "1.0.3","resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz","integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",- "dev": true,"license": "MIT"},"node_modules/escape-latex": {@@ -12620,7 +12568,6 @@"version": "1.8.1","resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz","integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.6"@@ -12647,7 +12594,6 @@"version": "3.0.7","resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz","integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",- "dev": true,"license": "MIT","dependencies": {"eventsource-parser": "^3.0.1"@@ -12729,7 +12675,6 @@"version": "5.2.1","resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz","integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",- "dev": true,"license": "MIT","dependencies": {"accepts": "^2.0.0",@@ -12770,11 +12715,13 @@}},"node_modules/express-rate-limit": {- "version": "7.5.1",- "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.1.tgz",- "integrity": "sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw==",- "dev": true,+ "version": "8.5.2",+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.2.tgz",+ "integrity": "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==","license": "MIT",+ "dependencies": {+ "ip-address": "^10.2.0"+ },"engines": {"node": ">= 16"},@@ -12883,7 +12830,6 @@"version": "3.1.2","resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz","integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==",- "dev": true,"funding": [{"type": "github",@@ -13089,7 +13035,6 @@"version": "2.1.1","resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz","integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",- "dev": true,"license": "MIT","dependencies": {"debug": "^4.4.0",@@ -13346,7 +13291,6 @@"version": "0.2.0","resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz","integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.6"@@ -13370,7 +13314,6 @@"version": "2.0.0","resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz","integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.8"@@ -13542,11 +13485,19 @@"node": ">= 0.4"}},+ "node_modules/generic-pool": {+ "version": "3.9.0",+ "resolved": "https://registry.npmjs.org/generic-pool/-/generic-pool-3.9.0.tgz",+ "integrity": "sha512-hymDOu5B53XvN4QT9dBmZxPX4CWhBPPLguTZ9MMFeFa/Kg0xWVfylOVNlJji/E7yTZWFd/q9GO5TxDLq156D7g==",+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },"node_modules/get-intrinsic": {"version": "1.3.0","resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz","integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",- "dev": true,"license": "MIT","dependencies": {"call-bind-apply-helpers": "^1.0.2",@@ -13580,7 +13531,6 @@"version": "1.0.1","resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz","integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",- "dev": true,"license": "MIT","dependencies": {"dunder-proto": "^1.0.1",@@ -13900,7 +13850,6 @@"version": "1.2.0","resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz","integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.4"@@ -13987,7 +13936,6 @@"version": "1.1.0","resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz","integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.4"@@ -14028,9 +13976,7 @@"version": "4.12.25","resolved": "https://registry.npmjs.org/hono/-/hono-4.12.25.tgz","integrity": "sha512-2NFaIyNVgJmBs/ecmtGzlmluTFs5cHEWGTdu0t1HBwYzoGXOL5nUQBRMXsXWla5i4KkG//QMzVP88m1+I3fdAQ==",- "dev": true,"license": "MIT",- "optional": true,"engines": {"node": ">=16.9.0"}@@ -14074,7 +14020,6 @@"version": "2.0.1","resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz","integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",- "dev": true,"license": "MIT","dependencies": {"depd": "~2.0.0",@@ -14504,7 +14449,6 @@"version": "10.2.0","resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz","integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",- "dev": true,"license": "MIT","engines": {"node": ">= 12"@@ -14514,7 +14458,6 @@"version": "1.9.1","resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz","integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.10"@@ -14906,7 +14849,6 @@"version": "4.0.0","resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz","integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",- "dev": true,"license": "MIT"},"node_modules/is-regex": {@@ -15114,7 +15056,6 @@"version": "2.0.0","resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz","integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",- "dev": true,"license": "ISC"},"node_modules/isobject": {@@ -15397,9 +15338,7 @@"version": "8.0.2","resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz","integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",- "dev": true,- "license": "BSD-2-Clause",- "optional": true+ "license": "BSD-2-Clause"},"node_modules/json-stable-stringify-without-jsonify": {"version": "1.0.1",@@ -16344,7 +16283,6 @@"version": "1.1.0","resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz","integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.4"@@ -16374,6 +16312,131 @@"node": ">= 18"}},+ "node_modules/mcp-handler": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/mcp-handler/-/mcp-handler-1.1.0.tgz",+ "integrity": "sha512-MVCES7g18gcoZy+R/3v5nadkUMzMAWdos8jRl6DyljOKvd2/ZKDmwlCjL6zp4vo+7FeCXOYL1uWinHWlkKAAUg==",+ "license": "Apache-2.0",+ "dependencies": {+ "chalk": "^5.3.0",+ "commander": "^11.1.0",+ "redis": "^4.6.0"+ },+ "bin": {+ "create-mcp-route": "dist/cli/index.js",+ "mcp-adapter": "dist/cli/index.js",+ "mcp-handler": "dist/cli/index.js"+ },+ "peerDependencies": {+ "@modelcontextprotocol/sdk": "1.26.0",+ "next": ">=13.0.0"+ },+ "peerDependenciesMeta": {+ "@modelcontextprotocol/sdk": {+ "optional": false+ },+ "next": {+ "optional": true+ }+ }+ },+ "node_modules/mcp-handler/node_modules/@redis/bloom": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-1.2.0.tgz",+ "integrity": "sha512-HG2DFjYKbpNmVXsa0keLHp/3leGJz1mjh09f2RLGGLQZzSHpkmZWuwJbAvo3QcRY8p80m5+ZdXZdYOSBLlp7Cg==",+ "license": "MIT",+ "peerDependencies": {+ "@redis/client": "^1.0.0"+ }+ },+ "node_modules/mcp-handler/node_modules/@redis/client": {+ "version": "1.6.1",+ "resolved": "https://registry.npmjs.org/@redis/client/-/client-1.6.1.tgz",+ "integrity": "sha512-/KCsg3xSlR+nCK8/8ZYSknYxvXHwubJrU82F3Lm1Fp6789VQ0/3RJKfsmRXjqfaTA++23CvC3hqmqe/2GEt6Kw==",+ "license": "MIT",+ "dependencies": {+ "cluster-key-slot": "1.1.2",+ "generic-pool": "3.9.0",+ "yallist": "4.0.0"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/mcp-handler/node_modules/@redis/graph": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@redis/graph/-/graph-1.1.1.tgz",+ "integrity": "sha512-FEMTcTHZozZciLRl6GiiIB4zGm5z5F3F6a6FZCyrfxdKOhFlGkiAqlexWMBzCi4DcRoyiOsuLfW+cjlGWyExOw==",+ "license": "MIT",+ "peerDependencies": {+ "@redis/client": "^1.0.0"+ }+ },+ "node_modules/mcp-handler/node_modules/@redis/json": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/@redis/json/-/json-1.0.7.tgz",+ "integrity": "sha512-6UyXfjVaTBTJtKNG4/9Z8PSpKE6XgSyEb8iwaqDcy+uKrd/DGYHTWkUdnQDyzm727V7p21WUMhsqz5oy65kPcQ==",+ "license": "MIT",+ "peerDependencies": {+ "@redis/client": "^1.0.0"+ }+ },+ "node_modules/mcp-handler/node_modules/@redis/search": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/@redis/search/-/search-1.2.0.tgz",+ "integrity": "sha512-tYoDBbtqOVigEDMAcTGsRlMycIIjwMCgD8eR2t0NANeQmgK/lvxNAvYyb6bZDD4frHRhIHkJu2TBRvB0ERkOmw==",+ "license": "MIT",+ "peerDependencies": {+ "@redis/client": "^1.0.0"+ }+ },+ "node_modules/mcp-handler/node_modules/@redis/time-series": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-1.1.0.tgz",+ "integrity": "sha512-c1Q99M5ljsIuc4YdaCwfUEXsofakb9c8+Zse2qxTadu8TalLXuAESzLvFAvNVbkmSlvlzIQOLpBCmWI9wTOt+g==",+ "license": "MIT",+ "peerDependencies": {+ "@redis/client": "^1.0.0"+ }+ },+ "node_modules/mcp-handler/node_modules/chalk": {+ "version": "5.6.2",+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz",+ "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==",+ "license": "MIT",+ "engines": {+ "node": "^12.17.0 || ^14.13 || >=16.0.0"+ },+ "funding": {+ "url": "https://github.com/chalk/chalk?sponsor=1"+ }+ },+ "node_modules/mcp-handler/node_modules/commander": {+ "version": "11.1.0",+ "resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz",+ "integrity": "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==",+ "license": "MIT",+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/mcp-handler/node_modules/redis": {+ "version": "4.7.1",+ "resolved": "https://registry.npmjs.org/redis/-/redis-4.7.1.tgz",+ "integrity": "sha512-S1bJDnqLftzHXHP8JsT5II/CtHWQrASX5K96REjWjlmWKrviSOLWmM7QnRLstAWsu1VBBV1ffV6DzCvxNP0UJQ==",+ "license": "MIT",+ "workspaces": [+ "./packages/*"+ ],+ "dependencies": {+ "@redis/bloom": "1.2.0",+ "@redis/client": "1.6.1",+ "@redis/graph": "1.1.1",+ "@redis/json": "1.0.7",+ "@redis/search": "1.2.0",+ "@redis/time-series": "1.1.0"+ }+ },"node_modules/md5": {"version": "2.3.0","resolved": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz",@@ -16402,7 +16465,6 @@"version": "1.1.0","resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz","integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.8"@@ -16447,7 +16509,6 @@"version": "2.0.0","resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz","integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",- "dev": true,"license": "MIT","engines": {"node": ">=18"@@ -16482,7 +16543,6 @@"version": "1.54.0","resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz","integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.6"@@ -16492,7 +16552,6 @@"version": "3.0.2","resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz","integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",- "dev": true,"license": "MIT","dependencies": {"mime-db": "^1.54.0"@@ -16751,7 +16810,6 @@"version": "2.1.3","resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz","integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",- "dev": true,"license": "MIT"},"node_modules/mustache": {@@ -17310,7 +17368,6 @@"version": "1.13.4","resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz","integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.4"@@ -17458,7 +17515,6 @@"version": "2.4.1","resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz","integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",- "dev": true,"license": "MIT","dependencies": {"ee-first": "1.1.1"@@ -17481,7 +17537,6 @@"version": "1.4.0","resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz","integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",- "dev": true,"license": "ISC","dependencies": {"wrappy": "1"@@ -17902,7 +17957,6 @@"version": "1.3.3","resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz","integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.8"@@ -17947,7 +18001,6 @@"version": "3.1.1","resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz","integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",- "dev": true,"license": "MIT","engines": {"node": ">=8"@@ -17980,7 +18033,6 @@"version": "8.4.2","resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz","integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",- "dev": true,"license": "MIT","funding": {"type": "opencollective",@@ -18180,7 +18232,6 @@"version": "5.0.1","resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz","integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",- "dev": true,"license": "MIT","engines": {"node": ">=16.20.0"@@ -18756,6 +18807,39 @@"sharp": "^0.34.5"}},+ "node_modules/promptfoo/node_modules/@modelcontextprotocol/sdk": {+ "version": "1.22.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.22.0.tgz",+ "integrity": "sha512-VUpl106XVTCpDmTBil2ehgJZjhyLY2QZikzF8NvTXtLRF1CvO5iEE2UNZdVIUer35vFOwMKYeUGbjJtvPWan3g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ajv": "^8.17.1",+ "ajv-formats": "^3.0.1",+ "content-type": "^1.0.5",+ "cors": "^2.8.5",+ "cross-spawn": "^7.0.5",+ "eventsource": "^3.0.2",+ "eventsource-parser": "^3.0.0",+ "express": "^5.0.1",+ "express-rate-limit": "^7.5.0",+ "pkce-challenge": "^5.0.0",+ "raw-body": "^3.0.0",+ "zod": "^3.23.8",+ "zod-to-json-schema": "^3.24.1"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@cfworker/json-schema": "^4.1.1"+ },+ "peerDependenciesMeta": {+ "@cfworker/json-schema": {+ "optional": true+ }+ }+ },"node_modules/promptfoo/node_modules/ajv": {"version": "8.20.0","resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",@@ -18799,6 +18883,22 @@"url": "https://dotenvx.com"}},+ "node_modules/promptfoo/node_modules/express-rate-limit": {+ "version": "7.5.1",+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.1.tgz",+ "integrity": "sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://github.com/sponsors/express-rate-limit"+ },+ "peerDependencies": {+ "express": ">= 4.11"+ }+ },"node_modules/promptfoo/node_modules/fsevents": {"version": "2.3.2","resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",@@ -19167,7 +19267,6 @@"version": "2.0.7","resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz","integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",- "dev": true,"license": "MIT","dependencies": {"forwarded": "0.2.0",@@ -19455,7 +19554,6 @@"version": "6.15.2","resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz","integrity": "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==",- "dev": true,"license": "BSD-3-Clause","dependencies": {"side-channel": "^1.1.0"@@ -19508,7 +19606,6 @@"version": "1.2.1","resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz","integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.6"@@ -19518,7 +19615,6 @@"version": "3.0.2","resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz","integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",- "dev": true,"license": "MIT","dependencies": {"bytes": "~3.1.2",@@ -19534,7 +19630,6 @@"version": "0.7.2","resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz","integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",- "dev": true,"license": "MIT","dependencies": {"safer-buffer": ">= 2.1.2 < 3.0.0"@@ -20138,7 +20233,6 @@"version": "2.2.0","resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz","integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",- "dev": true,"license": "MIT","dependencies": {"debug": "^4.4.0",@@ -20294,7 +20388,6 @@"version": "2.1.2","resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz","integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",- "dev": true,"license": "MIT"},"node_modules/saxes": {@@ -20340,7 +20433,6 @@"version": "1.2.1","resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz","integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",- "dev": true,"license": "MIT","dependencies": {"debug": "^4.4.3",@@ -20367,7 +20459,6 @@"version": "2.2.1","resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz","integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",- "dev": true,"license": "MIT","dependencies": {"encodeurl": "^2.0.0",@@ -20442,7 +20533,6 @@"version": "1.2.0","resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz","integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",- "dev": true,"license": "ISC"},"node_modules/shallow-clone": {@@ -20536,7 +20626,6 @@"version": "2.0.0","resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz","integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",- "dev": true,"license": "MIT","dependencies": {"shebang-regex": "^3.0.0"@@ -20549,7 +20638,6 @@"version": "3.0.0","resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz","integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",- "dev": true,"license": "MIT","engines": {"node": ">=8"@@ -20559,7 +20647,6 @@"version": "1.1.0","resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz","integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",- "dev": true,"license": "MIT","dependencies": {"es-errors": "^1.3.0",@@ -20579,7 +20666,6 @@"version": "1.0.0","resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz","integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",- "dev": true,"license": "MIT","dependencies": {"es-errors": "^1.3.0",@@ -20596,7 +20682,6 @@"version": "1.0.1","resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz","integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",- "dev": true,"license": "MIT","dependencies": {"call-bound": "^1.0.2",@@ -20615,7 +20700,6 @@"version": "1.0.2","resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz","integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",- "dev": true,"license": "MIT","dependencies": {"call-bound": "^1.0.2",@@ -20948,7 +21032,6 @@"version": "2.0.2","resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz","integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.8"@@ -21706,7 +21789,6 @@"version": "1.0.1","resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz","integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",- "dev": true,"license": "MIT","engines": {"node": ">=0.6"@@ -21936,7 +22018,6 @@"version": "2.1.0","resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz","integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",- "dev": true,"license": "MIT","dependencies": {"content-type": "^2.0.0",@@ -21955,7 +22036,6 @@"version": "2.0.0","resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz","integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",- "dev": true,"license": "MIT","engines": {"node": ">=18"@@ -22197,7 +22277,6 @@"version": "1.0.0","resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz","integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.8"@@ -22405,7 +22484,6 @@"version": "1.1.2","resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz","integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.8"@@ -22697,7 +22775,6 @@"version": "2.0.2","resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz","integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",- "dev": true,"license": "ISC","dependencies": {"isexe": "^2.0.0"@@ -23001,7 +23078,6 @@"version": "1.0.2","resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz","integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",- "dev": true,"license": "ISC"},"node_modules/ws": {@@ -23105,6 +23181,12 @@"node": ">=0.4"}},+ "node_modules/yallist": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",+ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",+ "license": "ISC"+ },"node_modules/yaml": {"version": "2.9.0","resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",@@ -23189,7 +23271,6 @@"version": "3.25.2","resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz","integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",- "dev": true,"license": "ISC","peerDependencies": {"zod": "^3.25.28 || ^4"diff --git a/package.json b/package.jsonindex 87a58ad..4174ec8 100644--- a/package.json+++ b/package.json@@ -19,6 +19,7 @@"@ai-sdk/openai": "^3.0.2","@ai-sdk/react": "^3.0.5","@hookform/resolvers": "^5.2.2",+ "@modelcontextprotocol/sdk": "^1.26.0","@nivo/bar": "^0.99.0","@nivo/calendar": "^0.99.0","@nivo/core": "^0.99.0",@@ -56,6 +57,7 @@"lucide-react": "^0.469.0","mammoth": "^1.12.0","markdown-it": "^14.1.0",+ "mcp-handler": "^1.1.0","next": "^15.5.18","next-auth": "^5.0.0-beta.30","next-themes": "^0.4.4",diff --git a/prisma/migrations/20260626144202_add_mcp_access_token/migration.sql b/prisma/migrations/20260626144202_add_mcp_access_token/migration.sqlnew file mode 100644index 0000000..2e58873--- /dev/null+++ b/prisma/migrations/20260626144202_add_mcp_access_token/migration.sql@@ -0,0 +1,25 @@+-- AlterTable+ALTER TABLE "Job" ADD COLUMN "createdVia" TEXT;++-- CreateTable+CREATE TABLE "McpAccessToken" (+ "id" TEXT NOT NULL PRIMARY KEY,+ "userId" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "tokenHash" TEXT NOT NULL,+ "tokenPrefix" TEXT NOT NULL,+ "scopes" TEXT NOT NULL,+ "expiresAt" DATETIME NOT NULL,+ "lastUsedAt" DATETIME,+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ CONSTRAINT "McpAccessToken_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE+);++-- CreateIndex+CREATE UNIQUE INDEX "McpAccessToken_tokenHash_key" ON "McpAccessToken"("tokenHash");++-- CreateIndex+CREATE INDEX "McpAccessToken_userId_idx" ON "McpAccessToken"("userId");++-- CreateIndex+CREATE UNIQUE INDEX "McpAccessToken_userId_name_key" ON "McpAccessToken"("userId", "name");diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 03ef766..b28ab1b 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -13,27 +13,28 @@ datasource db {}model User {- id String @id @default(uuid())- name String- email String @unique- password String- createdAt DateTime @default(now())- jobsApplied Job[]- JobTitle JobTitle[]- Location Location[]- Company Company[]- JobSource JobSource[]- Contact Contact[]- Profile Profile[]- Activity Activity[]- ActivityType ActivityType[]- Task Task[]- Automation Automation[]- Settings UserSettings?- ApiKey ApiKey[]- Note Note[]- Tag Tag[]- Question Question[]+ id String @id @default(uuid())+ name String+ email String @unique+ password String+ createdAt DateTime @default(now())+ jobsApplied Job[]+ JobTitle JobTitle[]+ Location Location[]+ Company Company[]+ JobSource JobSource[]+ Contact Contact[]+ Profile Profile[]+ Activity Activity[]+ ActivityType ActivityType[]+ Task Task[]+ Automation Automation[]+ Settings UserSettings?+ ApiKey ApiKey[]+ Note Note[]+ Tag Tag[]+ Question Question[]+ McpAccessToken McpAccessToken[]}model ApiKey {@@ -310,6 +311,9 @@ model Job {discoveryStatus String?discoveredAt DateTime?+ // MCP provenance: which agent/token created this job (null = UI or automation)+ createdVia String?+@@index([userId, automationId])@@index([userId, discoveryStatus])}@@ -464,3 +468,19 @@ model Question {@@index([createdBy])}++model McpAccessToken {+ id String @id @default(uuid())+ userId String+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)+ name String+ tokenHash String @unique+ tokenPrefix String+ scopes String // JSON array string; v1 always ["jobs:write"]+ expiresAt DateTime+ lastUsedAt DateTime?+ createdAt DateTime @default(now())++ @@unique([userId, name])+ @@index([userId])+}diff --git a/src/actions/job.actions.ts b/src/actions/job.actions.tsindex fab0c15..c60aa87 100644--- a/src/actions/job.actions.ts+++ b/src/actions/job.actions.ts@@ -303,6 +303,8 @@ export const createJobSource = async (}};+import { createJobRecord } from "@/lib/jobs/createJobRecord";+export const addJob = async (data: z.infer<typeof AddJobFormSchema>,): Promise<any | undefined> => {@@ -331,30 +333,23 @@ export const addJob = async (tags,} = data;- const tagIds = tags ?? [];-- const job = await prisma.job.create({- data: {- jobTitleId: title,- companyId: company,- locationId: location,- statusId: status,- jobSourceId: source,- salaryRange: salaryRange,- createdAt: new Date(),- dueDate: dueDate,- appliedDate: dateApplied,- description: jobDescription,- jobType: type,- userId: user.id,- jobUrl,- applied,- resumeId: resume,- coverLetterId: coverLetter,- ...(tagIds.length > 0- ? { tags: { connect: tagIds.map((id) => ({ id })) } }- : {}),- },+ const job = await createJobRecord({+ jobTitleId: title,+ companyId: company,+ locationId: location,+ statusId: status,+ jobSourceId: source,+ salaryRange,+ dueDate,+ appliedDate: dateApplied,+ description: jobDescription,+ jobType: type,+ userId: user.id,+ jobUrl,+ applied,+ resumeId: resume,+ coverLetterId: coverLetter,+ tagIds: tags ?? [],});revalidatePath("/dashboard");return { job, success: true };diff --git a/src/actions/mcpToken.actions.ts b/src/actions/mcpToken.actions.tsnew file mode 100644index 0000000..1467639--- /dev/null+++ b/src/actions/mcpToken.actions.ts@@ -0,0 +1,113 @@+"use server";++import prisma from "@/lib/db";+import { getCurrentUser } from "@/utils/user.utils";+import { handleError } from "@/lib/utils";+import { generateToken } from "@/lib/mcp/tokens";+import { APP_CONSTANTS } from "@/lib/constants";++export interface PublicTokenMeta {+ id: string;+ name: string;+ tokenPrefix: string;+ scopes: string[];+ expiresAt: Date;+ lastUsedAt: Date | null;+ createdAt: Date;+}++export async function createMcpToken(input: {+ name: string;+ expiryDays: 30 | 90 | 365;+}): Promise<+ | { success: true; token: string; record: PublicTokenMeta }+ | { success: false; message: string }+> {+ try {+ const user = await getCurrentUser();+ if (!user) throw new Error("Not authenticated");++ const count = await prisma.mcpAccessToken.count({ where: { userId: user.id } });+ if (count >= APP_CONSTANTS.MCP_TOKEN_MAX_PER_USER) {+ return {+ success: false,+ message: `You can have at most ${APP_CONSTANTS.MCP_TOKEN_MAX_PER_USER} MCP tokens. Revoke one before creating another.`,+ };+ }++ const { plaintext, hash, prefix } = generateToken();+ const expiresAt = new Date(Date.now() + input.expiryDays * 24 * 60 * 60 * 1000);++ const record = await prisma.mcpAccessToken.create({+ data: {+ userId: user.id,+ name: input.name.trim(),+ tokenHash: hash,+ tokenPrefix: prefix,+ scopes: JSON.stringify(["jobs:write"]),+ expiresAt,+ },+ });++ return {+ success: true,+ token: plaintext,+ record: toPublicMeta(record),+ };+ } catch (error: any) {+ if (error?.code === "P2002") {+ return { success: false, message: `A token named "${input.name}" already exists. Choose a different name.` };+ }+ const result = handleError(error, "Failed to create MCP token.");+ return { success: false, message: result?.message ?? "Failed to create MCP token." };+ }+}++export async function listMcpTokens(): Promise<PublicTokenMeta[]> {+ try {+ const user = await getCurrentUser();+ if (!user) throw new Error("Not authenticated");++ const records = await prisma.mcpAccessToken.findMany({+ where: { userId: user.id },+ orderBy: { createdAt: "desc" },+ });++ return records.map(toPublicMeta);+ } catch {+ return [];+ }+}++export async function revokeMcpToken(id: string): Promise<{ success: boolean; message?: string }> {+ try {+ const user = await getCurrentUser();+ if (!user) throw new Error("Not authenticated");++ await prisma.mcpAccessToken.delete({ where: { id, userId: user.id } });+ return { success: true };+ } catch (error) {+ const result = handleError(error, "Failed to revoke MCP token.");+ return { success: false, message: result?.message ?? "Failed to revoke MCP token." };+ }+}++function toPublicMeta(record: {+ id: string;+ name: string;+ tokenPrefix: string;+ scopes: string;+ expiresAt: Date;+ lastUsedAt: Date | null;+ createdAt: Date;+}): PublicTokenMeta {+ return {+ id: record.id,+ name: record.name,+ tokenPrefix: record.tokenPrefix,+ scopes: JSON.parse(record.scopes) as string[],+ expiresAt: record.expiresAt,+ lastUsedAt: record.lastUsedAt,+ createdAt: record.createdAt,+ };+}diff --git a/src/actions/tag.actions.ts b/src/actions/tag.actions.tsindex a5595b1..fab62d5 100644--- a/src/actions/tag.actions.ts+++ b/src/actions/tag.actions.ts@@ -3,6 +3,7 @@ import prisma from "@/lib/db";import { handleError } from "@/lib/utils";import { getCurrentUser } from "@/utils/user.utils";import { APP_CONSTANTS } from "@/lib/constants";+import { resolveTag as resolveTagCore } from "@/lib/jobs/resolve";export const getAllTags = async (): Promise<any | undefined> => {try {@@ -62,19 +63,11 @@ export const createTag = async (label: string): Promise<any | undefined> => {throw new Error("Not authenticated");}- const trimmed = label.trim();- if (!trimmed) {+ if (!label.trim()) {throw new Error("Tag label cannot be empty.");}- const value = trimmed.toLowerCase();-- const tag = await prisma.tag.upsert({- where: { value_createdBy: { value, createdBy: user.id } },- update: {},- create: { label: trimmed, value, createdBy: user.id },- });-+ const { created: _, ...tag } = await resolveTagCore(label, user.id);return { data: tag, success: true };} catch (error) {const msg = "Failed to create tag. ";diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.tsnew file mode 100644index 0000000..d0a200a--- /dev/null+++ b/src/app/api/mcp/route.ts@@ -0,0 +1,70 @@+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";+import { resolveMcpToken } from "@/lib/mcp/auth";+import { McpAddJobInputShape, McpAddJobSchema } from "@/models/mcp.schema";+import { handleAddJob } from "@/lib/mcp/tools/addJob";++function isMcpEnabled(): boolean {+ const env = process.env.MCP_ENABLED;+ if (env === "true") return true;+ if (env === "false") return false;+ // Default: on in dev, off in production+ return process.env.NODE_ENV !== "production";+}++async function handler(req: Request): Promise<Response> {+ if (!isMcpEnabled()) {+ return new Response("Not Found", { status: 404 });+ }++ const auth = await resolveMcpToken(req);+ if (!auth.ok) {+ return new Response(JSON.stringify({ error: auth.error }), {+ status: auth.status,+ headers: { "Content-Type": "application/json" },+ });+ }++ if (!auth.scopes.includes("jobs:write")) {+ return new Response(JSON.stringify({ error: "Insufficient scope. Required: jobs:write" }), {+ status: 403,+ headers: { "Content-Type": "application/json" },+ });+ }++ const { userId, tokenName } = auth;++ const server = new McpServer({ name: "jobsync", version: "1.0.0" });++ server.tool(+ "add_job",+ "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.",+ McpAddJobInputShape,+ async (rawInput) => {+ const parsed = McpAddJobSchema.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 handleAddJob(parsed.data, userId, tokenName);+ },+ );++ const transport = new WebStandardStreamableHTTPServerTransport({+ sessionIdGenerator: undefined, // stateless mode+ enableJsonResponse: true, // return plain JSON instead of SSE stream+ });++ await server.connect(transport);+ const response = await transport.handleRequest(req);+ await server.close();++ return response;+}++// GET is for SSE server-push streams — not supported in stateless mode+async function getHandler(): Promise<Response> {+ return new Response("Method Not Allowed", { status: 405 });+}++export { getHandler as GET, handler as POST, handler as DELETE };diff --git a/src/app/dashboard/settings/page.tsx b/src/app/dashboard/settings/page.tsxindex f3d2fa8..175c89c 100644--- a/src/app/dashboard/settings/page.tsx+++ b/src/app/dashboard/settings/page.tsx@@ -4,6 +4,7 @@ import { useState } from "react";import AiSettings from "@/components/settings/AiSettings";import ApiKeySettings from "@/components/settings/ApiKeySettings";import DisplaySettings from "@/components/settings/DisplaySettings";+import McpAccessSettings from "@/components/settings/McpAccessSettings";import SettingsSidebar, { type SettingsSection } from "@/components/settings/SettingsSidebar";function Settings() {@@ -23,6 +24,7 @@ function Settings() {{activeSection === "ai-provider" && <AiSettings />}{activeSection === "api-keys" && <ApiKeySettings />}{activeSection === "appearance" && <DisplaySettings />}+ {activeSection === "mcp-access" && <McpAccessSettings />}</div></div></div>diff --git a/src/components/myjobs/JobDetails.tsx b/src/components/myjobs/JobDetails.tsxindex 5954c69..69eb17d 100644--- a/src/components/myjobs/JobDetails.tsx+++ b/src/components/myjobs/JobDetails.tsx@@ -125,6 +125,13 @@ function JobDetails({ job }: { job: JobResponse }) {))}</div>)}+ {job.createdVia && (+ <div className="my-1 ml-4">+ <Badge variant="outline" className="text-xs text-muted-foreground">+ via {job.createdVia}+ </Badge>+ </div>+ )}{job.jobUrl && (<div className="my-3 ml-4"><span className="font-semibold mr-2">Job URL:</span>diff --git a/src/components/settings/McpAccessSettings.tsx b/src/components/settings/McpAccessSettings.tsxnew file mode 100644index 0000000..6998ff8--- /dev/null+++ b/src/components/settings/McpAccessSettings.tsx@@ -0,0 +1,321 @@+"use client";++import { useEffect, useState } from "react";+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card";+import { Button } from "../ui/button";+import { Input } from "../ui/input";+import { Badge } from "../ui/badge";+import { Label } from "../ui/label";+import { toast } from "../ui/use-toast";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "../ui/dialog";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "../ui/select";+import { Loader2, Plus, Trash2, Copy, Check } from "lucide-react";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+} from "../ui/alert-dialog";+import {+ createMcpToken,+ listMcpTokens,+ revokeMcpToken,+ type PublicTokenMeta,+} from "@/actions/mcpToken.actions";+import { APP_CONSTANTS } from "@/lib/constants";+import { format } from "date-fns";++function CopyButton({ text }: { text: string }) {+ const [copied, setCopied] = useState(false);+ const copy = () => {+ navigator.clipboard.writeText(text);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ };+ return (+ <Button variant="outline" size="sm" onClick={copy} className="shrink-0">+ {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}+ </Button>+ );+}++function CodeSnippet({ label, code }: { label: string; code: string }) {+ return (+ <div className="space-y-1">+ <p className="text-xs text-muted-foreground font-medium">{label}</p>+ <div className="flex gap-2 items-start">+ <pre className="flex-1 bg-muted rounded p-2 text-xs overflow-x-auto whitespace-pre-wrap break-all">{code}</pre>+ <CopyButton text={code} />+ </div>+ </div>+ );+}++function TokenRevealDialog({+ token,+ tokenName,+ mcpUrl,+ onClose,+}: {+ token: string;+ tokenName: string;+ mcpUrl: string;+ onClose: () => void;+}) {+ const ocSnippet = JSON.stringify(+ {+ mcpServers: {+ jobsync: {+ type: "streamable-http",+ url: mcpUrl,+ headers: { Authorization: `Bearer ${token}` },+ },+ },+ },+ null,+ 2,+ );++ const claudeSnippet = `npx mcp-remote ${mcpUrl} --header "Authorization: Bearer ${token}"`;++ return (+ <Dialog open onOpenChange={(open) => !open && onClose()}>+ <DialogContent className="max-w-lg">+ <DialogHeader>+ <DialogTitle>Token Created — Save It Now</DialogTitle>+ <DialogDescription>+ This is the only time you can see the full token. Copy it before closing.+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <div className="space-y-1">+ <Label className="text-xs">Your token</Label>+ <div className="flex gap-2 items-center">+ <Input readOnly value={token} className="font-mono text-xs" />+ <CopyButton text={token} />+ </div>+ </div>+ <div className="space-y-3">+ <p className="text-xs font-medium text-muted-foreground">Client config snippets</p>+ <CodeSnippet label="OpenClaw / Hermes (streamable-http)" code={ocSnippet} />+ <CodeSnippet label="Claude Desktop (via mcp-remote)" code={claudeSnippet} />+ </div>+ </div>+ <DialogFooter>+ <Button onClick={onClose}>I saved my token</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++export default function McpAccessSettings() {+ const [tokens, setTokens] = useState<PublicTokenMeta[]>([]);+ const [isLoading, setIsLoading] = useState(true);+ const [generating, setGenerating] = useState(false);+ const [revoking, setRevoking] = useState<string | null>(null);++ const [showGenerateDialog, setShowGenerateDialog] = useState(false);+ const [tokenName, setTokenName] = useState("");+ const [expiryDays, setExpiryDays] = useState<30 | 90 | 365>(+ APP_CONSTANTS.MCP_TOKEN_EXPIRY_DEFAULT_DAYS as 30 | 90 | 365,+ );++ const [revealedToken, setRevealedToken] = useState<{ token: string; name: string } | null>(null);++ const mcpUrl =+ typeof window !== "undefined"+ ? `${window.location.origin}/api/mcp`+ : "/api/mcp";++ const fetchTokens = async () => {+ setIsLoading(true);+ const result = await listMcpTokens();+ setTokens(result);+ setIsLoading(false);+ };++ useEffect(() => { fetchTokens(); }, []);++ const handleGenerate = async () => {+ if (!tokenName.trim()) return;+ setGenerating(true);+ const result = await createMcpToken({ name: tokenName.trim(), expiryDays });+ setGenerating(false);+ if (!result.success) {+ toast({ title: "Error", description: result.message, variant: "destructive" });+ return;+ }+ setRevealedToken({ token: result.token, name: result.record.name });+ setShowGenerateDialog(false);+ setTokenName("");+ setExpiryDays(APP_CONSTANTS.MCP_TOKEN_EXPIRY_DEFAULT_DAYS as 30 | 90 | 365);+ await fetchTokens();+ };++ const handleRevoke = async (id: string) => {+ setRevoking(id);+ const result = await revokeMcpToken(id);+ setRevoking(null);+ if (!result.success) {+ toast({ title: "Error", description: result.message ?? "Failed to revoke", variant: "destructive" });+ return;+ }+ setTokens((prev) => prev.filter((t) => t.id !== id));+ toast({ title: "Token revoked" });+ };++ return (+ <div className="space-y-6">+ {revealedToken && (+ <TokenRevealDialog+ token={revealedToken.token}+ tokenName={revealedToken.name}+ mcpUrl={mcpUrl}+ onClose={() => setRevealedToken(null)}+ />+ )}++ <Card>+ <CardHeader>+ <CardTitle>MCP Endpoint</CardTitle>+ <CardDescription>Connect AI agents to JobSync via the Model Context Protocol.</CardDescription>+ </CardHeader>+ <CardContent>+ <div className="space-y-1">+ <Label className="text-xs text-muted-foreground">Endpoint URL</Label>+ <div className="flex gap-2 items-center">+ <Input readOnly value={mcpUrl} className="font-mono text-sm" />+ <CopyButton text={mcpUrl} />+ </div>+ </div>+ </CardContent>+ </Card>++ <Card>+ <CardHeader className="flex-row items-start justify-between">+ <div>+ <CardTitle>Personal Access Tokens</CardTitle>+ <CardDescription>Tokens authenticate external agents to call MCP tools.</CardDescription>+ </div>+ <Button size="sm" onClick={() => setShowGenerateDialog(true)} disabled={isLoading}>+ <Plus className="h-4 w-4 mr-1" />+ Generate+ </Button>+ </CardHeader>+ <CardContent>+ {isLoading ? (+ <div className="flex items-center gap-2 text-muted-foreground text-sm">+ <Loader2 className="h-4 w-4 animate-spin" /> Loading tokens...+ </div>+ ) : tokens.length === 0 ? (+ <p className="text-sm text-muted-foreground">No MCP tokens yet. Generate one to get started.</p>+ ) : (+ <div className="space-y-3">+ {tokens.map((t) => (+ <div key={t.id} className="flex items-center justify-between border rounded p-3 gap-3">+ <div className="min-w-0 flex-1">+ <p className="font-medium text-sm truncate">{t.name}</p>+ <p className="text-xs text-muted-foreground font-mono">{t.tokenPrefix}…</p>+ <div className="flex flex-wrap gap-2 mt-1 text-xs text-muted-foreground">+ <span>Created {format(new Date(t.createdAt), "PP")}</span>+ <span>Expires {format(new Date(t.expiresAt), "PP")}</span>+ {t.lastUsedAt && <span>Last used {format(new Date(t.lastUsedAt), "PP")}</span>}+ </div>+ <div className="flex gap-1 mt-1">+ {t.scopes.map((s) => (+ <Badge key={s} variant="secondary" className="text-xs">{s}</Badge>+ ))}+ </div>+ </div>+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button variant="ghost" size="icon" disabled={revoking === t.id} title="Revoke token">+ {revoking === t.id ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4 text-destructive" />}+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Revoke “{t.name}”?</AlertDialogTitle>+ <AlertDialogDescription>+ Any agent using this token will immediately lose access. This cannot be undone.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction onClick={() => handleRevoke(t.id)}>Revoke</AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ ))}+ </div>+ )}+ </CardContent>+ </Card>++ <Dialog open={showGenerateDialog} onOpenChange={setShowGenerateDialog}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Generate MCP Token</DialogTitle>+ <DialogDescription>+ Name this token after the client (e.g. ChatGPT, Hermes, Claude Desktop) — it's shown as the source on jobs this token creates.+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <div className="space-y-2">+ <Label>Token name</Label>+ <Input+ placeholder="e.g. Claude Desktop"+ value={tokenName}+ onChange={(e) => setTokenName(e.target.value)}+ onKeyDown={(e) => e.key === "Enter" && handleGenerate()}+ />+ </div>+ <div className="space-y-2">+ <Label>Expires in</Label>+ <Select+ value={String(expiryDays)}+ onValueChange={(v) => setExpiryDays(Number(v) as 30 | 90 | 365)}+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {APP_CONSTANTS.MCP_TOKEN_EXPIRY_PRESETS.map((d) => (+ <SelectItem key={d} value={String(d)}>{d} days</SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </div>+ <DialogFooter>+ <Button variant="outline" onClick={() => setShowGenerateDialog(false)}>Cancel</Button>+ <Button onClick={handleGenerate} disabled={generating || !tokenName.trim()}>+ {generating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}+ Generate+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ );+}diff --git a/src/components/settings/SettingsSidebar.tsx b/src/components/settings/SettingsSidebar.tsxindex 47dd5f5..39f8d65 100644--- a/src/components/settings/SettingsSidebar.tsx+++ b/src/components/settings/SettingsSidebar.tsx@@ -1,10 +1,10 @@"use client";-import { Bot, Key, Palette } from "lucide-react";+import { Bot, Key, Palette, Plug } from "lucide-react";import { Button } from "../ui/button";import { cn } from "@/lib/utils";-export type SettingsSection = "ai-provider" | "api-keys" | "appearance";+export type SettingsSection = "ai-provider" | "api-keys" | "appearance" | "mcp-access";const SETTINGS_SECTIONS: {id: SettingsSection;@@ -14,6 +14,7 @@ const SETTINGS_SECTIONS: {{ id: "ai-provider", label: "AI Provider", icon: Bot },{ id: "api-keys", label: "API Keys", icon: Key },{ id: "appearance", label: "Appearance", icon: Palette },+ { id: "mcp-access", label: "MCP Access", icon: Plug },];interface SettingsSidebarProps {diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex 3bc6fbb..86ca12c 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -45,6 +45,16 @@ export const APP_CONSTANTS = {AUTOMATION_MAX_MANUAL_RUNS_PER_HOUR: 5,AUTOMATION_RATE_LIMIT_WINDOW_MS: 60 * 60 * 1000, // 1 hour+ // MCP server settings+ MCP_DUPLICATE_WINDOW_DAYS: 30,+ MCP_TOKEN_EXPIRY_PRESETS: [30, 90, 365] as const,+ MCP_TOKEN_EXPIRY_DEFAULT_DAYS: 90,+ MCP_TOKEN_MAX_PER_USER: 10,+ MCP_RATE_LIMIT_MAX: 30,+ MCP_RATE_LIMIT_WINDOW_MS: 60 * 60 * 1000,+ MCP_DEFAULT_JOB_TYPE: "Full-time",+ MCP_DEFAULT_STATUS: "draft",+// File uploadsUPLOADS_DIR: process.env.NODE_ENV !== "production" ? "data" : "/data",MAX_RESUME_FILE_SIZE_BYTES: 5 * 1024 * 1024, // 5 MBdiff --git a/src/lib/jobs/createJobFromNames.ts b/src/lib/jobs/createJobFromNames.tsnew file mode 100644index 0000000..752c032--- /dev/null+++ b/src/lib/jobs/createJobFromNames.ts@@ -0,0 +1,205 @@+import prisma from "@/lib/db";+import { APP_CONSTANTS } from "@/lib/constants";+import { normalizeJobUrl } from "@/lib/scraper/utils";+import { createJobRecord } from "@/lib/jobs/createJobRecord";+import {+ resolveCompany,+ resolveJobTitle,+ resolveLocation,+ resolveJobSource,+ resolveJobType,+ resolveJobStatus,+ resolveTags,+ type ResolvedEntity,+} from "./resolve";++export interface CreateJobFromNamesInput {+ company: string;+ jobTitle: string;+ jobDescription: string;+ location?: string;+ source?: string;+ jobType?: string;+ status?: string;+ dueDate?: Date | null;+ applied?: boolean;+ appliedDate?: Date | null;+ jobUrl?: string;+ salaryRange?: string;+ tags?: string[];+ allowDuplicate?: boolean;+ createdVia?: string;+}++export interface CreateJobFromNamesResult {+ created: boolean;+ jobId?: string;+ duplicateOf?: { id: string; title: string; company: string };+ resolutions: ResolvedEntity[];+ message: string;+}++export async function createJobFromNames(+ input: CreateJobFromNamesInput,+ userId: string,+): Promise<CreateJobFromNamesResult> {+ const {+ company,+ jobTitle,+ jobDescription,+ location,+ source,+ jobType,+ status,+ dueDate = null,+ applied = false,+ appliedDate,+ jobUrl,+ salaryRange,+ tags = [],+ allowDuplicate = false,+ createdVia,+ } = input;++ // Resolve Bucket A and B in parallel where possible+ const [+ resolvedCompany,+ resolvedTitle,+ resolvedLocation,+ resolvedSource,+ resolvedTagsResult,+ jobTypeValue,+ statusId,+ ] = await Promise.all([+ resolveCompany(company, userId),+ resolveJobTitle(jobTitle, userId),+ location ? resolveLocation(location, userId) : Promise.resolve(null),+ source ? resolveJobSource(source, userId) : Promise.resolve(null),+ resolveTags(tags, userId, APP_CONSTANTS.MAX_JOB_TAGS),+ Promise.resolve(resolveJobType(jobType)),+ resolveJobStatus(status),+ ]);++ const resolutions: ResolvedEntity[] = [+ resolvedCompany,+ resolvedTitle,+ ...(resolvedLocation ? [resolvedLocation] : []),+ ...(resolvedSource ? [resolvedSource] : []),+ ...resolvedTagsResult.resolved,+ ];++ // Duplicate detection+ if (!allowDuplicate) {+ const duplicate = await detectDuplicate(+ userId,+ resolvedCompany.id,+ resolvedTitle.id,+ jobUrl,+ );+ if (duplicate) {+ return {+ created: false,+ duplicateOf: duplicate,+ resolutions,+ message: buildDuplicateMessage(duplicate, resolutions),+ };+ }+ }++ // Default appliedDate if applied is true but no date provided+ const resolvedAppliedDate = applied && !appliedDate ? new Date() : (appliedDate ?? null);++ const job = await createJobRecord({+ jobTitleId: resolvedTitle.id,+ companyId: resolvedCompany.id,+ locationId: resolvedLocation?.id ?? null,+ statusId,+ jobSourceId: resolvedSource?.id ?? null,+ salaryRange: salaryRange ?? null,+ dueDate,+ appliedDate: resolvedAppliedDate,+ description: jobDescription,+ jobType: jobTypeValue,+ userId,+ jobUrl: jobUrl ? normalizeJobUrl(jobUrl) : null,+ applied,+ tagIds: resolvedTagsResult.resolved.map((t) => t.id),+ createdVia: createdVia ?? null,+ });++ const message = buildSuccessMessage(resolutions, resolvedTagsResult.dropped, job.id);++ return {+ created: true,+ jobId: job.id,+ resolutions,+ message,+ };+}++async function detectDuplicate(+ userId: string,+ companyId: string,+ jobTitleId: string,+ jobUrl?: string,+): Promise<{ id: string; title: string; company: string } | null> {+ // Tier 1 — URL match (no time window)+ if (jobUrl) {+ const normalized = normalizeJobUrl(jobUrl);+ const byUrl = await prisma.job.findFirst({+ where: { userId, jobUrl: normalized },+ select: { id: true, JobTitle: { select: { label: true } }, Company: { select: { label: true } } },+ });+ if (byUrl) {+ return { id: byUrl.id, title: byUrl.JobTitle.label, company: byUrl.Company.label };+ }+ }++ // Tier 2 — company + title within window+ const windowDays = APP_CONSTANTS.MCP_DUPLICATE_WINDOW_DAYS;+ const since = new Date(Date.now() - windowDays * 24 * 60 * 60 * 1000);+ const byNameWindow = await prisma.job.findFirst({+ where: {+ userId,+ companyId,+ jobTitleId,+ createdAt: { gte: since },+ },+ select: { id: true, JobTitle: { select: { label: true } }, Company: { select: { label: true } } },+ });+ if (byNameWindow) {+ return { id: byNameWindow.id, title: byNameWindow.JobTitle.label, company: byNameWindow.Company.label };+ }++ return null;+}++function buildSuccessMessage(+ resolutions: ResolvedEntity[],+ droppedTags: string[],+ jobId: string,+): string {+ const parts = resolutions.map((r) => {+ const action = r.created ? "Created" : "Matched";+ return `${action} ${r.label}`;+ });+ let msg = parts.join("; ") + `. Job created (id: ${jobId}).`;+ if (droppedTags.length > 0) {+ msg += ` Dropped tags exceeding limit: ${droppedTags.join(", ")}.`;+ }+ return msg;+}++function buildDuplicateMessage(+ dup: { id: string; title: string; company: string },+ resolutions: ResolvedEntity[],+): string {+ const parts = resolutions.map((r) => {+ const action = r.created ? "Created" : "Matched";+ return `${action} ${r.label}`;+ });+ return (+ `Duplicate detected — existing job "${dup.title}" at "${dup.company}" (id: ${dup.id}). ` ++ `Pass allowDuplicate: true to force create. Resolutions: ${parts.join("; ")}.`+ );+}diff --git a/src/lib/jobs/createJobRecord.ts b/src/lib/jobs/createJobRecord.tsnew file mode 100644index 0000000..b4ae93c--- /dev/null+++ b/src/lib/jobs/createJobRecord.ts@@ -0,0 +1,30 @@+import prisma from "@/lib/db";++export async function createJobRecord(fields: {+ jobTitleId: string;+ companyId: string;+ locationId?: string | null;+ statusId: string;+ jobSourceId?: string | null;+ salaryRange?: string | null;+ dueDate?: Date | null;+ appliedDate?: Date | null;+ description: string;+ jobType: string;+ userId: string;+ jobUrl?: string | null;+ applied?: boolean;+ resumeId?: string | null;+ coverLetterId?: string | null;+ tagIds?: string[];+ createdVia?: string | null;+}) {+ const { tagIds = [], ...rest } = fields;+ return prisma.job.create({+ data: {+ ...rest,+ createdAt: new Date(),+ ...(tagIds.length > 0 ? { tags: { connect: tagIds.map((id) => ({ id })) } } : {}),+ },+ });+}diff --git a/src/lib/jobs/resolve.ts b/src/lib/jobs/resolve.tsnew file mode 100644index 0000000..71503d8--- /dev/null+++ b/src/lib/jobs/resolve.ts@@ -0,0 +1,142 @@+import prisma from "@/lib/db";+import { JOB_TYPES } from "@/models/job.model";++export interface ResolvedEntity {+ id: string;+ label: string;+ created: boolean;+}++// Extended shape needed so createTag's callers (TagInput.tsx) get back the full Tag+export interface ResolvedTag extends ResolvedEntity {+ value: string;+ createdBy: string;+}++// Bucket A — resolve-or-create by exact-normalized value++export async function resolveCompany(+ label: string,+ userId: string,+): Promise<ResolvedEntity> {+ const trimmed = label.trim();+ const value = trimmed.toLowerCase();+ const existing = await prisma.company.findUnique({+ where: { value_createdBy: { value, createdBy: userId } },+ });+ if (existing) return { id: existing.id, label: existing.label, created: false };+ const created = await prisma.company.create({+ data: { label: trimmed, value, createdBy: userId },+ });+ return { id: created.id, label: created.label, created: true };+}++export async function resolveJobTitle(+ label: string,+ userId: string,+): Promise<ResolvedEntity> {+ const trimmed = label.trim();+ const value = trimmed.toLowerCase();+ const existing = await prisma.jobTitle.findUnique({+ where: { value_createdBy: { value, createdBy: userId } },+ });+ if (existing) return { id: existing.id, label: existing.label, created: false };+ const created = await prisma.jobTitle.create({+ data: { label: trimmed, value, createdBy: userId },+ });+ return { id: created.id, label: created.label, created: true };+}++export async function resolveLocation(+ label: string,+ userId: string,+): Promise<ResolvedEntity> {+ const trimmed = label.trim();+ const value = trimmed.toLowerCase();+ const existing = await prisma.location.findUnique({+ where: { value_createdBy: { value, createdBy: userId } },+ });+ if (existing) return { id: existing.id, label: existing.label, created: false };+ const record = await prisma.location.create({+ data: { label: trimmed, value, createdBy: userId },+ });+ return { id: record.id, label: record.label, created: true };+}++export async function resolveJobSource(+ label: string,+ userId: string,+): Promise<ResolvedEntity> {+ const trimmed = label.trim();+ const value = trimmed.toLowerCase();+ const existing = await prisma.jobSource.findUnique({+ where: { value_createdBy: { value, createdBy: userId } },+ });+ if (existing) return { id: existing.id, label: existing.label, created: false };+ const record = await prisma.jobSource.create({+ data: { label: trimmed, value, createdBy: userId },+ });+ return { id: record.id, label: record.label, created: true };+}++export async function resolveTag(+ label: string,+ userId: string,+): Promise<ResolvedTag> {+ const trimmed = label.trim();+ const value = trimmed.toLowerCase();+ const existing = await prisma.tag.findUnique({+ where: { value_createdBy: { value, createdBy: userId } },+ });+ if (existing) return { id: existing.id, label: existing.label, value: existing.value, createdBy: existing.createdBy, created: false };+ const tag = await prisma.tag.create({+ data: { label: trimmed, value, createdBy: userId },+ });+ return { id: tag.id, label: tag.label, value: tag.value, createdBy: tag.createdBy, created: true };+}++export async function resolveTags(+ labels: string[],+ userId: string,+ maxTags: number,+): Promise<{ resolved: ResolvedEntity[]; dropped: string[] }> {+ const seen = new Set<string>();+ const unique: string[] = [];+ for (const l of labels) {+ const trimmed = l.trim();+ if (!trimmed) continue;+ const key = trimmed.toLowerCase();+ if (!seen.has(key)) {+ seen.add(key);+ unique.push(trimmed);+ }+ }++ const toResolve = unique.slice(0, maxTags);+ const dropped = unique.slice(maxTags);++ const resolved = await Promise.all(toResolve.map((l) => resolveTag(l, userId)));+ return { resolved, dropped };+}++// Bucket B — resolve-ONLY, never create++export function resolveJobType(input?: string): string {+ if (!input) return "Full-time";+ const valid = Object.values(JOB_TYPES) as string[];+ const match = valid.find((v) => v.toLowerCase() === input.toLowerCase());+ if (match) return match;+ throw new Error(`Invalid jobType "${input}". Valid values: ${valid.join(", ")}`);+}++export async function resolveJobStatus(value?: string): Promise<string> {+ const target = (value ?? "draft").toLowerCase();+ const status = await prisma.jobStatus.findUnique({ where: { value: target } });+ if (!status) {+ const all = await prisma.jobStatus.findMany({ select: { value: true } });+ throw new Error(+ `Invalid status "${target}". Valid values: ${all.map((s) => s.value).join(", ")}`,+ );+ }+ return status.id;+}diff --git a/src/lib/mcp/auth.ts b/src/lib/mcp/auth.tsnew file mode 100644index 0000000..d5ff6f5--- /dev/null+++ b/src/lib/mcp/auth.ts@@ -0,0 +1,42 @@+import prisma from "@/lib/db";+import { hashToken } from "./tokens";++type AuthSuccess = { ok: true; userId: string; scopes: string[]; tokenName: string };+type AuthFailure = { ok: false; status: 401 | 403; error: string };++export async function resolveMcpToken(req: Request): Promise<AuthSuccess | AuthFailure> {+ const authHeader = req.headers.get("authorization") ?? "";+ if (!authHeader.startsWith("Bearer ")) {+ return { ok: false, status: 401, error: "Missing or malformed Authorization header" };+ }++ const plaintext = authHeader.slice("Bearer ".length).trim();+ if (!plaintext) {+ return { ok: false, status: 401, error: "Empty token" };+ }++ const tokenHash = hashToken(plaintext);+ const record = await prisma.mcpAccessToken.findUnique({ where: { tokenHash } });++ if (!record) {+ return { ok: false, status: 401, error: "Invalid token" };+ }++ if (record.expiresAt < new Date()) {+ return { ok: false, status: 401, error: "Token expired" };+ }++ // Fire-and-forget lastUsedAt update+ prisma.mcpAccessToken.update({+ where: { id: record.id },+ data: { lastUsedAt: new Date() },+ }).catch(() => {});++ let scopes: string[];+ try {+ scopes = JSON.parse(record.scopes) as string[];+ } catch {+ return { ok: false, status: 401, error: "Malformed token scopes" };+ }+ return { ok: true, userId: record.userId, scopes, tokenName: record.name };+}diff --git a/src/lib/mcp/rate-limit.ts b/src/lib/mcp/rate-limit.tsnew file mode 100644index 0000000..6725cfd--- /dev/null+++ b/src/lib/mcp/rate-limit.ts@@ -0,0 +1,40 @@+import { APP_CONSTANTS } from "@/lib/constants";++interface RateLimitEntry {+ count: number;+ resetTime: number;+}++const store = new Map<string, RateLimitEntry>();++const MAX = APP_CONSTANTS.MCP_RATE_LIMIT_MAX;+const WINDOW = APP_CONSTANTS.MCP_RATE_LIMIT_WINDOW_MS;+const CLEANUP_THRESHOLD = 500;++export function checkMcpRateLimit(userId: string): {+ allowed: boolean;+ remaining: number;+ resetIn: number;+} {+ const now = Date.now();++ if (store.size > CLEANUP_THRESHOLD) {+ for (const [key, entry] of store) {+ if (now > entry.resetTime) store.delete(key);+ }+ }++ const entry = store.get(userId);++ if (!entry || now > entry.resetTime) {+ store.set(userId, { count: 1, resetTime: now + WINDOW });+ return { allowed: true, remaining: MAX - 1, resetIn: WINDOW };+ }++ if (entry.count >= MAX) {+ return { allowed: false, remaining: 0, resetIn: entry.resetTime - now };+ }++ entry.count++;+ return { allowed: true, remaining: MAX - entry.count, resetIn: entry.resetTime - now };+}diff --git a/src/lib/mcp/tokens.ts b/src/lib/mcp/tokens.tsnew file mode 100644index 0000000..9ff209c--- /dev/null+++ b/src/lib/mcp/tokens.ts@@ -0,0 +1,14 @@+import { createHash, randomBytes } from "crypto";++const TOKEN_PREFIX = "jsync_";++export function generateToken(): { plaintext: string; hash: string; prefix: string } {+ const plaintext = TOKEN_PREFIX + randomBytes(32).toString("base64url");+ const hash = hashToken(plaintext);+ const prefix = plaintext.slice(0, 12);+ return { plaintext, hash, prefix };+}++export function hashToken(plaintext: string): string {+ return createHash("sha256").update(plaintext).digest("hex");+}diff --git a/src/lib/mcp/tools/addJob.ts b/src/lib/mcp/tools/addJob.tsnew file mode 100644index 0000000..0032460--- /dev/null+++ b/src/lib/mcp/tools/addJob.ts@@ -0,0 +1,37 @@+import { z } from "zod";+import { McpAddJobSchema } from "@/models/mcp.schema";+import { createJobFromNames } from "@/lib/jobs/createJobFromNames";+import { checkMcpRateLimit } from "@/lib/mcp/rate-limit";++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;++export async function handleAddJob(+ input: z.infer<typeof McpAddJobSchema>,+ userId: string,+ tokenName: 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 createJobFromNames(+ { ...input, createdVia: tokenName },+ userId,+ );+ return { content: [{ type: "text", text: result.message }] };+ } catch (err: any) {+ return {+ content: [{ type: "text", text: `Error: ${err?.message ?? "Unknown error"}` }],+ };+ }+}diff --git a/src/middleware.ts b/src/middleware.tsindex 389fd8d..ee008e0 100644--- a/src/middleware.ts+++ b/src/middleware.ts@@ -8,6 +8,6 @@ export const config = {matcher: ["/dashboard","/dashboard/:path*",- "/api/((?!auth).*)",+ "/api/((?!auth|mcp).*)",],};diff --git a/src/models/job.model.ts b/src/models/job.model.tsindex 975bbb7..56f9576 100644--- a/src/models/job.model.ts+++ b/src/models/job.model.ts@@ -51,6 +51,7 @@ export interface JobResponse {matchScore?: number | null;matchData?: string | null;tags?: Tag[];+ createdVia?: string | null;_count?: { Notes?: number };}diff --git a/src/models/mcp.schema.ts b/src/models/mcp.schema.tsnew file mode 100644index 0000000..0e2d577--- /dev/null+++ b/src/models/mcp.schema.ts@@ -0,0 +1,28 @@+import { z } from "zod";++// Raw input shape for MCP tool registration (no transforms — SDK uses this for JSON schema)+export const McpAddJobInputShape = {+ company: z.string().min(1, "company is required"),+ jobTitle: z.string().min(1, "jobTitle is required"),+ jobDescription: z.string().min(10, "jobDescription must be at least 10 characters"),+ location: z.string().optional().describe("City, province/state, country, or 'Remote'"),+ source: z.string().optional().describe("Job board or site the listing came from, e.g. 'LinkedIn', 'Indeed', 'company website'"),+ jobType: z.string().optional().describe("Employment type: 'Full-time', 'Part-time', or 'Contract'"),+ status: z.string().optional().describe("Application status: draft, applied, interview, offer, rejected, expired, or archived. Defaults to 'draft'"),+ dueDate: z.string().datetime({ offset: true }).optional().describe("Application deadline as an ISO-8601 datetime string"),+ applied: z.boolean().optional().describe("Set true if you have already submitted the application"),+ appliedDate: z.string().datetime({ offset: true }).optional().describe("Date the application was submitted as an ISO-8601 datetime string"),+ jobUrl: z.string().url().optional().describe("Direct URL to the job posting"),+ salaryRange: z.string().optional().describe("Salary range as a free-form string, e.g. '$120k–$150k' or '100,000 CAD'"),+ tags: z.array(z.string()).optional().describe("Skills required for the job (max 10 applied, extras are dropped). Tags are created if they don't exist. e.g. ['React', 'TypeScript', 'Node.js']"),+ allowDuplicate: z.boolean().optional(),+};++// Full schema with transforms for parsing raw MCP input in the handler+export const McpAddJobSchema = z.object({+ ...McpAddJobInputShape,+ 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 McpAddJobInput = z.infer<typeof McpAddJobSchema>;