promptlike-mcp 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.1 — 2026-09-28
4
+
5
+ - Official MCP Registry name is now `io.github.zeynepaslierhan/promptlike-mcp` (user namespace; the org namespace cannot be verified by the registry). No code changes.
6
+
7
+ ## 0.4.0 — 2026-09-27
8
+
9
+ Save from the agent.
10
+
11
+ - **New: `save_prompt`** (`title`, `content`, `description?`, `project?`,
12
+ `tags?`) and **`update_prompt`** (`name`, `content`, `changelog?`,
13
+ `bump?: patch|minor|major`, `project?`). Add-only: a new prompt or a new
14
+ version — nothing is ever deleted. Saving the same title + content again, or
15
+ updating with the current content, changes nothing (safe to retry).
16
+ `update_prompt` needs the exact title or id; it never guesses. Plan limits
17
+ apply as on the web and come back as a plain message with the upgrade link.
18
+ Content that looks like a live key/token is refused. Writes use your
19
+ `ple login` session; without it, the tools say so.
20
+ - **New: `save-this` prompt** — `/mcp__promptlike__save-this` asks the agent to
21
+ pull the reusable instruction out of the conversation, mark `{{variables}}`,
22
+ show it to you and call `save_prompt`.
23
+ - **New: resources** — every prompt as `promptlike://<repo>/<prompt>`
24
+ (`text/markdown`, current version), plus a resource template. In Claude Code
25
+ they are `@`-mentionable.
26
+ - **New: `suggest_prompts(task)`** — best matches from your own library for a
27
+ task, for agents without hooks. `get_prompt` accepts `via: "suggestion"`.
28
+ - List/read responses carry the 2026-07-28 cache hints (`ttlMs`,
29
+ `cacheScope: private`); prompts/resources announce `listChanged` after a save.
30
+ - Uses are recorded with their surface (tool / slash prompt / resource) and the
31
+ client name, so Insights can tell agents apart.
32
+ - Tool annotations: read tools `readOnlyHint`; write tools
33
+ `destructiveHint: false`, `idempotentHint: true`.
34
+ - **Fixed:** `{{constructor}}` and similar names no longer fill from JavaScript
35
+ built-ins when left empty.
36
+ - MCP sampling is not used (deprecated in the 2026-07-28 spec).
37
+
3
38
  ## 0.3.0 — 2026-09-27
4
39
 
5
40
  Your library in the `/` menu.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # promptlike-mcp
2
2
 
3
- MCP (Model Context Protocol) server for [PromptLikeEngineer](https://promptlikeengineer.com) — gives AI agents **read-only** access to your prompt library.
3
+ MCP (Model Context Protocol) server for [PromptLikeEngineer](https://promptlikeengineer.com) — gives AI agents your prompt library: read it, fill it, get suggestions from it, and save good prompts back to it (**add-only**: a new prompt or a new version, never a delete).
4
4
 
5
5
  Your prompts stay where you saved them; your agent pulls them by name at the moment it needs them. No copy-paste, no stale duplicates in system prompts.
6
6
 
@@ -34,18 +34,35 @@ The server also implements the MCP **prompts** primitive (`prompts/list`, `promp
34
34
  | `{{file}}`, `{{focus}}` in the body | optional arguments `file`, `focus` — empty ones stay as `{{name}}` |
35
35
  | Repo + description | shown as the prompt description, e.g. `[ai-os] Reviews a diff` |
36
36
 
37
- Up to 500 prompts are listed (most recently updated first); the list is cached for 30 seconds, so a prompt you just saved shows up within half a minute. The four tools below are unchanged.
37
+ Up to 500 prompts are listed (most recently updated first); the list is cached for 30 seconds, and a save through this server refreshes it at once.
38
38
 
39
- ## Tools (read-only)
39
+ One built-in prompt sits next to yours: **`save-this`** (`/mcp__promptlike__save-this`). It asks the agent to pull the reusable instruction out of the conversation, mark `{{variables}}`, show it to you and save it with `save_prompt`.
40
+
41
+ ## Resources (v0.4+) — `@`-mention a prompt
42
+
43
+ Every prompt is also a resource, `promptlike://<repo>/<prompt>` (`text/markdown`, current version). Clients with resource support let you attach one directly — in Claude Code, type `@` and pick it. List and read responses carry cache hints (`ttlMs`, `cacheScope: private`).
44
+
45
+ ## Tools
40
46
 
41
47
  | Tool | What it does |
42
48
  |---|---|
43
49
  | `list_prompts` | List your prompts (optional `tag` filter). Includes each prompt's `{{variable}}` names. |
44
50
  | `search_prompts` | Search by title/description. |
45
- | `get_prompt` | Full content by name/id/short-id, optional `version` pin. |
51
+ | `get_prompt` | Full content by name/id/short-id, optional `version` pin. `via: "suggestion"` when fetching a suggested prompt. |
46
52
  | `fill_variables` | Fetch + substitute `{{variables}}`, returns ready-to-use text (unfilled ones reported in `missing_variables`). |
53
+ | `suggest_prompts` | Up to 3 prompts from your own library that fit a task (call once at the start of a non-trivial task). |
54
+ | `save_prompt` | **Write.** New prompt: `title`, `content`, optional `description`, `project` (repo; default: your most recent repo you can edit), `tags`. |
55
+ | `update_prompt` | **Write.** New version of an existing prompt: exact title or id, full new `content`, optional `changelog`, `bump` (`patch`/`minor`/`major`). |
56
+
57
+ ### How writes behave
58
+
59
+ - **Add-only.** There is no delete tool; `update_prompt` keeps every earlier version (roll back on the web or with `ple rollback`).
60
+ - **Safe to retry.** Same title + content → "already saved"; content equal to the current version → no new version. A title that exists with different content is reported instead of duplicated.
61
+ - **Your account, your limits.** Writes use your `ple login` session and the same plan limits as the web; hitting one returns a plain message with the upgrade link and saves nothing. Viewer access to a shared repo cannot write.
62
+ - **No secrets.** Content that looks like an API key or token is refused — use a `{{variable}}`.
63
+ - **Exact names only for updates.** A fuzzy match is answered with "did you mean…", never written to.
47
64
 
48
- Writing/improving prompts is intentionally out of scope — an agent can never burn your AI tokens or mutate your library through this server.
65
+ The server never spends your AI tokens (no improve), and it does not use MCP sampling.
49
66
 
50
67
  ## Notes
51
68
 
@@ -12,17 +12,41 @@
12
12
  * refresh, 429/hata gövdelerini temiz mesajlara map'leme.
13
13
  */
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.NOT_LOGGED_IN = void 0;
15
+ exports.ApiError = exports.NOT_LOGGED_IN = void 0;
16
16
  exports.ensureAuthed = ensureAuthed;
17
17
  exports.listPromptsPage = listPromptsPage;
18
18
  exports.listPrompts = listPrompts;
19
19
  exports.listProjects = listProjects;
20
20
  exports.getPromptDetail = getPromptDetail;
21
+ exports.buildUseEventBody = buildUseEventBody;
22
+ exports.sanitizeClientName = sanitizeClientName;
21
23
  exports.recordPromptUse = recordPromptUse;
24
+ exports.createPrompt = createPrompt;
25
+ exports.savePromptVersion = savePromptVersion;
26
+ exports.addPromptTag = addPromptTag;
27
+ exports.suggestPrompts = suggestPrompts;
22
28
  const constants_1 = require("./constants");
23
29
  const config_1 = require("./config");
24
30
  exports.NOT_LOGGED_IN = 'Not logged in. Run `ple login` in a terminal first (install: npm i -g promptlike).';
25
31
  const SESSION_EXPIRED = 'Session expired. Run `ple login` in a terminal to sign in again.';
32
+ /**
33
+ * HTTP error with the status kept, so write tools can tell a plan limit
34
+ * (403 + upgradeUrl / 429 LIMIT_EXCEEDED) from a real failure.
35
+ */
36
+ class ApiError extends Error {
37
+ constructor(message, status, code, upgradeUrl) {
38
+ super(message);
39
+ this.name = 'ApiError';
40
+ this.status = status;
41
+ this.code = code;
42
+ this.upgradeUrl = upgradeUrl;
43
+ }
44
+ /** True for plan-limit responses (prompt / version / project caps). */
45
+ get isPlanLimit() {
46
+ return Boolean(this.upgradeUrl) || this.code === 'LIMIT_EXCEEDED';
47
+ }
48
+ }
49
+ exports.ApiError = ApiError;
26
50
  function buildUrl(path, query) {
27
51
  const u = new URL(constants_1.API_BASE_URL + path);
28
52
  if (query) {
@@ -42,9 +66,8 @@ async function toError(res) {
42
66
  catch {
43
67
  // Non-JSON error body — generic message below.
44
68
  }
45
- if (body.error)
46
- return new Error(body.error);
47
- return new Error(`Request failed (${res.status}).`);
69
+ const message = body.error || `Request failed (${res.status}).`;
70
+ return new ApiError(message, res.status, body.code, body.upgradeUrl);
48
71
  }
49
72
  function getAccessTokenOrThrow() {
50
73
  const config = (0, config_1.readConfig)();
@@ -107,6 +130,14 @@ async function apiFetch(path, opts = {}) {
107
130
  await refreshSession();
108
131
  return apiFetch(path, { ...opts, _retried: true });
109
132
  }
133
+ if (res.status === 429 && !res.headers.get('retry-after')) {
134
+ // 429 without Retry-After can be a plan limit body (import route) —
135
+ // surface its message instead of a misleading "rate limited".
136
+ const err = await toError(res);
137
+ if (err.isPlanLimit)
138
+ throw err;
139
+ throw new ApiError('Rate limited. Retry in a few seconds.', 429, err.code);
140
+ }
110
141
  if (res.status === 429) {
111
142
  const retryAfter = res.headers.get('retry-after');
112
143
  // Agent'lar back-off yapabilsin diye süre mesajda açık.
@@ -168,12 +199,80 @@ async function getPromptDetail(id) {
168
199
  throw err;
169
200
  }
170
201
  }
202
+ /** POST /use body. Client is trimmed to the server's charset/length. */
203
+ function buildUseEventBody(opts) {
204
+ const body = {
205
+ surface: opts.surface,
206
+ client: sanitizeClientName(opts.client) ?? `promptlike-mcp/${constants_1.MCP_VERSION}`,
207
+ via: opts.via === 'suggestion' ? 'suggestion' : 'direct',
208
+ };
209
+ if (typeof opts.version === 'number' && Number.isInteger(opts.version) && opts.version > 0) {
210
+ body.version = opts.version;
211
+ }
212
+ return body;
213
+ }
214
+ /** Same charset/length rule as the server (`sanitizeClient`): ≤64, `[A-Za-z0-9._@/ -]`. */
215
+ function sanitizeClientName(v) {
216
+ if (!v)
217
+ return null;
218
+ const cleaned = v.replace(/[^A-Za-z0-9._@/ -]/g, '').slice(0, 64).trim();
219
+ return cleaned || null;
220
+ }
171
221
  /**
172
- * Kullanım kaydı — get_prompt/fill_variables sonrası fire-and-forget
173
- * (CLI copy/get/show ile aynı desen). Hata YUTULUR.
222
+ * Kullanım kaydı — get_prompt/fill_variables/prompts.get/resources.read
223
+ * sonrası fire-and-forget (CLI copy/get/show ile aynı desen). Gövde yüzeyi,
224
+ * istemciyi ve `via`yı taşır (W1-1 olay defteri). Hata YUTULUR.
174
225
  */
175
- function recordPromptUse(promptId) {
176
- apiFetch(`/api/prompts/${promptId}/use`, { method: 'POST' }).catch(() => {
226
+ function recordPromptUse(promptId, opts = { surface: 'mcp_tool' }) {
227
+ apiFetch(`/api/prompts/${promptId}/use`, { method: 'POST', body: buildUseEventBody(opts) }).catch(() => {
177
228
  /* sessiz — telemetri */
178
229
  });
179
230
  }
231
+ /**
232
+ * A single-body prompt goes into `contextText` — the same slot `ple sync` and
233
+ * the import route use — with the other two parts empty, so `versionText()`
234
+ * returns exactly what the agent saved.
235
+ */
236
+ async function createPrompt(input) {
237
+ return apiFetch('/api/prompts', {
238
+ method: 'POST',
239
+ body: {
240
+ isNew: true,
241
+ projectId: input.projectId,
242
+ title: input.title,
243
+ description: input.description ?? '',
244
+ roleText: '',
245
+ descriptionText: '',
246
+ contextText: input.content,
247
+ changelog: input.changelog ?? 'Saved from an agent via MCP',
248
+ source: 'mcp',
249
+ },
250
+ });
251
+ }
252
+ /** New version of an existing prompt (never deletes the old one). */
253
+ async function savePromptVersion(input) {
254
+ return apiFetch('/api/prompts', {
255
+ method: 'POST',
256
+ body: {
257
+ id: input.promptId,
258
+ roleText: '',
259
+ descriptionText: '',
260
+ contextText: input.content,
261
+ changelog: input.changelog ?? 'Updated from an agent via MCP',
262
+ source: 'mcp',
263
+ bumpMajor: input.bump === 'major',
264
+ bumpMinor: input.bump === 'minor',
265
+ },
266
+ });
267
+ }
268
+ /** Attach a tag by name (found or created in the prompt's repo). */
269
+ async function addPromptTag(promptId, tagName) {
270
+ await apiFetch(`/api/prompts/${promptId}/tags`, { method: 'POST', body: { tagName } });
271
+ }
272
+ /** Best matches for a task from the user's OWN library (server-side full text). */
273
+ async function suggestPrompts(task, limit = 3) {
274
+ const res = await apiFetch('/api/prompts/suggest', {
275
+ query: { task, limit },
276
+ });
277
+ return res.suggestions ?? [];
278
+ }
@@ -52,13 +52,19 @@ function slugifyPromptName(title) {
52
52
  function shortId(id) {
53
53
  return id.replace(/-/g, '').slice(0, 8).toLowerCase();
54
54
  }
55
- /** Prompt listesinden benzersiz, deterministik adlı katalog kurar. */
56
- function buildPromptCatalog(prompts) {
55
+ /**
56
+ * Prompt listesinden benzersiz, deterministik adlı katalog kurar.
57
+ * `reserved`: sunucunun kendi prompt adları (ör. `save-this`) — kullanıcının
58
+ * aynı slug'a düşen prompt'u çakışma sayılır ve id soneki alır.
59
+ */
60
+ function buildPromptCatalog(prompts, reserved = new Set()) {
57
61
  const base = prompts.map((p) => {
58
62
  const slug = slugifyPromptName(p.title);
59
63
  return { prompt: p, slug: slug || `prompt-${shortId(p.id)}` };
60
64
  });
61
65
  const counts = new Map();
66
+ for (const r of reserved)
67
+ counts.set(r, 1);
62
68
  for (const { slug } of base)
63
69
  counts.set(slug, (counts.get(slug) ?? 0) + 1);
64
70
  const seen = new Set();
@@ -36,7 +36,9 @@ function fillVariables(text, values) {
36
36
  if (!text)
37
37
  return '';
38
38
  return text.replace(VARIABLE_PATTERN, (whole, name) => {
39
- const value = values[name];
40
- return value !== undefined && value !== '' ? value : whole;
39
+ // Yalnız kendi anahtarları: {{constructor}} / {{toString}} gibi adlar
40
+ // Object.prototype'tan fonksiyon çekip metne "function Object()…" basmasın.
41
+ const value = Object.prototype.hasOwnProperty.call(values, name) ? values[name] : undefined;
42
+ return typeof value === 'string' && value !== '' ? value : whole;
41
43
  });
42
44
  }
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ /**
3
+ * MCP `resources` primitive (W1-3) — the user's library as
4
+ * `promptlike://<repo-slug>/<prompt-name>` resources, so clients that support
5
+ * resources can attach a prompt directly (Claude Code: `@` mention).
6
+ *
7
+ * Pure: builds on the prompts catalog (`buildPromptCatalog`), whose names are
8
+ * already unique across the whole library — so the URI is unique too and one
9
+ * lookup table serves prompts/get and resources/read.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.RESOURCE_TEMPLATE = exports.RESOURCE_MIME = exports.RESOURCE_SCHEME = void 0;
13
+ exports.repoSegment = repoSegment;
14
+ exports.resourceUri = resourceUri;
15
+ exports.parseResourceUri = parseResourceUri;
16
+ exports.toMcpResource = toMcpResource;
17
+ exports.findByUri = findByUri;
18
+ const mcpPrompts_1 = require("./mcpPrompts");
19
+ const promptVariables_1 = require("./promptVariables");
20
+ const promptText_1 = require("./promptText");
21
+ exports.RESOURCE_SCHEME = 'promptlike';
22
+ exports.RESOURCE_MIME = 'text/markdown';
23
+ /** URI template advertised via resources/templates/list. */
24
+ exports.RESOURCE_TEMPLATE = `${exports.RESOURCE_SCHEME}://{repo}/{prompt}`;
25
+ /** Repo segment: slug of the repo name; prompts without a repo fall under `library`. */
26
+ function repoSegment(projectName) {
27
+ return (0, mcpPrompts_1.slugifyPromptName)(projectName ?? '') || 'library';
28
+ }
29
+ function resourceUri(entry) {
30
+ return `${exports.RESOURCE_SCHEME}://${repoSegment(entry.prompt.project_name)}/${entry.name}`;
31
+ }
32
+ /** Parse `promptlike://<repo>/<name>` → the prompt name, or null when malformed. */
33
+ function parseResourceUri(uri) {
34
+ const m = /^promptlike:\/\/([a-z0-9-]+)\/([a-z0-9-]+)$/.exec(uri.trim());
35
+ return m ? { repo: m[1], name: m[2] } : null;
36
+ }
37
+ /** Only ISO timestamps are forwarded (the SDK validates `lastModified`). */
38
+ function isoOrUndefined(v) {
39
+ if (!v)
40
+ return undefined;
41
+ const t = Date.parse(v);
42
+ return Number.isFinite(t) ? new Date(t).toISOString() : undefined;
43
+ }
44
+ function toMcpResource(entry) {
45
+ const { prompt } = entry;
46
+ const vars = (0, promptVariables_1.extractVariables)((0, promptText_1.versionText)(prompt.current_version));
47
+ const descParts = [
48
+ prompt.project_name ? `[${prompt.project_name}]` : '',
49
+ (prompt.description ?? '').trim(),
50
+ vars.length > 0 ? `Variables: ${vars.map((v) => `{{${v}}}`).join(', ')}` : '',
51
+ ].filter(Boolean);
52
+ const out = {
53
+ uri: resourceUri(entry),
54
+ name: entry.name,
55
+ title: prompt.title,
56
+ mimeType: exports.RESOURCE_MIME,
57
+ };
58
+ if (descParts.length > 0)
59
+ out.description = descParts.join(' ');
60
+ const lastModified = isoOrUndefined(prompt.updated_at);
61
+ if (lastModified)
62
+ out.annotations = { lastModified };
63
+ return out;
64
+ }
65
+ /** Find a catalog entry by URI (repo segment must match too). */
66
+ function findByUri(entries, uri) {
67
+ const parsed = parseResourceUri(uri);
68
+ if (!parsed)
69
+ return undefined;
70
+ return entries.find((e) => e.name === parsed.name && repoSegment(e.prompt.project_name) === parsed.repo);
71
+ }
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ /**
3
+ * Input rules for the MCP write tools (W1-3: save_prompt / update_prompt).
4
+ *
5
+ * Pure — no network. Limits mirror the web API and `ple save` (title 200 /
6
+ * body 100K / description 1000; tags ≤10 × ≤50, same as the import route) so
7
+ * an agent gets a clear error instead of a silent server-side slice.
8
+ *
9
+ * Secret guard: an agent saving "the prompt from this conversation" can easily
10
+ * sweep a live key into it. A saved prompt syncs to the account and may one
11
+ * day be made public, so content that looks like a token is refused and the
12
+ * *kind* is named (never the value). Same patterns as the CLI's
13
+ * `secretGuard.ts` (`ple import --scan`) — copied, since the CLI package does
14
+ * not export internals (precedent: promptVariables).
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.MAX_TAG_LENGTH = exports.MAX_TAGS = exports.MAX_CHANGELOG = exports.MAX_DESCRIPTION = exports.MAX_CONTENT = exports.MAX_TITLE = void 0;
18
+ exports.findSecret = findSecret;
19
+ exports.cleanTitle = cleanTitle;
20
+ exports.cleanContent = cleanContent;
21
+ exports.checkSaveInput = checkSaveInput;
22
+ exports.checkUpdateInput = checkUpdateInput;
23
+ exports.sameContent = sameContent;
24
+ exports.MAX_TITLE = 200;
25
+ exports.MAX_CONTENT = 100000;
26
+ exports.MAX_DESCRIPTION = 1000;
27
+ exports.MAX_CHANGELOG = 500;
28
+ exports.MAX_TAGS = 10;
29
+ exports.MAX_TAG_LENGTH = 50;
30
+ const SECRET_PATTERNS = [
31
+ { label: 'Anthropic/OpenAI API key', re: /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}/ },
32
+ { label: 'AWS access key', re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/ },
33
+ { label: 'GitHub token', re: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}\b|\bgithub_pat_[A-Za-z0-9_]{30,}/ },
34
+ { label: 'GitLab token', re: /\bglpat-[A-Za-z0-9_-]{20,}/ },
35
+ { label: 'Slack token', re: /\bxox[abprs]-[A-Za-z0-9-]{10,}/ },
36
+ { label: 'Google API key', re: /\bAIza[0-9A-Za-z_-]{35}\b/ },
37
+ { label: 'Stripe key', re: /\b(?:sk|rk)_live_[A-Za-z0-9]{20,}/ },
38
+ { label: 'private key', re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
39
+ { label: 'JWT', re: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/ },
40
+ ];
41
+ /** Kind of secret found (never the value), or null when clean. */
42
+ function findSecret(text) {
43
+ for (const { label, re } of SECRET_PATTERNS) {
44
+ if (re.test(text))
45
+ return label;
46
+ }
47
+ return null;
48
+ }
49
+ // C0/C1 control characters except tab/newline/carriage return.
50
+ const CONTROL_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g;
51
+ /** Titles are one line: control chars and line breaks collapse to spaces. */
52
+ function cleanTitle(raw) {
53
+ return raw.replace(CONTROL_CHARS, ' ').replace(/[\r\n\t]+/g, ' ').replace(/\s{2,}/g, ' ').trim();
54
+ }
55
+ /** Body text: strip control chars, normalise line endings, trim the ends. */
56
+ function cleanContent(raw) {
57
+ return raw.replace(/\r\n?/g, '\n').replace(CONTROL_CHARS, '').trim();
58
+ }
59
+ function checkContent(raw) {
60
+ const content = cleanContent(raw);
61
+ if (!content)
62
+ return { ok: false, error: 'content is empty.' };
63
+ if (content.length > exports.MAX_CONTENT) {
64
+ return { ok: false, error: `content is too long (${content.length} chars, max ${exports.MAX_CONTENT}).` };
65
+ }
66
+ const secret = findSecret(content);
67
+ if (secret) {
68
+ return {
69
+ ok: false,
70
+ error: `content looks like it contains a ${secret}. Saved prompts sync to the account and can be made public — ` +
71
+ 'replace the value with a {{variable}} (e.g. {{api_key}}) and try again.',
72
+ };
73
+ }
74
+ return { ok: true, value: content };
75
+ }
76
+ /** Validate + normalise save_prompt input. */
77
+ function checkSaveInput(input) {
78
+ const title = cleanTitle(input.title);
79
+ if (!title)
80
+ return { ok: false, error: 'title is empty.' };
81
+ if (title.length > exports.MAX_TITLE) {
82
+ return { ok: false, error: `title is too long (${title.length} chars, max ${exports.MAX_TITLE}).` };
83
+ }
84
+ const content = checkContent(input.content);
85
+ if (!content.ok)
86
+ return content;
87
+ const description = cleanTitle(input.description ?? '');
88
+ if (description.length > exports.MAX_DESCRIPTION) {
89
+ return { ok: false, error: `description is too long (max ${exports.MAX_DESCRIPTION} chars).` };
90
+ }
91
+ if (findSecret(`${title}\n${description}`)) {
92
+ return { ok: false, error: 'title/description looks like it contains a secret. Remove it and try again.' };
93
+ }
94
+ const tags = [];
95
+ for (const raw of input.tags ?? []) {
96
+ const tag = cleanTitle(raw);
97
+ if (!tag)
98
+ continue;
99
+ if (tag.length > exports.MAX_TAG_LENGTH) {
100
+ return { ok: false, error: `tag '${tag.slice(0, 20)}…' is too long (max ${exports.MAX_TAG_LENGTH} chars).` };
101
+ }
102
+ if (!tags.some((t) => t.toLowerCase() === tag.toLowerCase()))
103
+ tags.push(tag);
104
+ }
105
+ if (tags.length > exports.MAX_TAGS)
106
+ return { ok: false, error: `too many tags (max ${exports.MAX_TAGS}).` };
107
+ return { ok: true, value: { title, content: content.value, description, tags } };
108
+ }
109
+ /** Validate + normalise update_prompt input. */
110
+ function checkUpdateInput(input) {
111
+ const content = checkContent(input.content);
112
+ if (!content.ok)
113
+ return content;
114
+ const changelog = input.changelog === undefined ? undefined : cleanTitle(input.changelog);
115
+ if (changelog !== undefined && changelog.length > exports.MAX_CHANGELOG) {
116
+ return { ok: false, error: `changelog is too long (max ${exports.MAX_CHANGELOG} chars).` };
117
+ }
118
+ return { ok: true, value: { content: content.value, changelog: changelog || undefined } };
119
+ }
120
+ /**
121
+ * Idempotency key for "same content": whitespace-insensitive at the ends and
122
+ * line-ending-insensitive, so a retried call with identical text is a no-op.
123
+ */
124
+ function sameContent(a, b) {
125
+ return cleanContent(a) === cleanContent(b);
126
+ }
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ /**
3
+ * save_prompt / update_prompt flows (W1-3, strategy F4) — "save from the agent".
4
+ *
5
+ * Guarantees:
6
+ * - Identity: every call goes through the signed-in user's token (the web API
7
+ * resolves the user; nothing here takes a user id).
8
+ * - Quota: plan limits are enforced by the API (pre-check + DB trigger). A
9
+ * limit response becomes a clean message with the upgrade link.
10
+ * - Idempotency (content-based, survives restarts): saving the same title +
11
+ * content into the same repo twice is a no-op that returns the existing
12
+ * prompt; updating with the current content creates no version. A retried
13
+ * tool call therefore never duplicates anything.
14
+ * - Safety: update_prompt needs an exact title / id — a fuzzy match could
15
+ * add a version to the wrong prompt. Old versions are never deleted.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.describeWriteError = describeWriteError;
19
+ exports.savePromptFlow = savePromptFlow;
20
+ exports.updatePromptFlow = updatePromptFlow;
21
+ const api_client_1 = require("./api-client");
22
+ const constants_1 = require("./constants");
23
+ const promptText_1 = require("./promptText");
24
+ const resolver_1 = require("./resolver");
25
+ const writeGuard_1 = require("./writeGuard");
26
+ const WRITE_ROLES = new Set(['owner', 'admin', 'editor']);
27
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
28
+ /** Plan-limit / API errors → one readable line for the agent to relay. */
29
+ function describeWriteError(err) {
30
+ if (err instanceof api_client_1.ApiError && err.isPlanLimit) {
31
+ const url = `${constants_1.API_BASE_URL}${err.upgradeUrl && err.upgradeUrl.startsWith('/') ? err.upgradeUrl : '/pricing'}`;
32
+ return `${err.message} Plan limit reached — nothing was saved. Upgrade: ${url}`;
33
+ }
34
+ return err instanceof Error ? err.message : 'Unexpected error.';
35
+ }
36
+ /** Target repo: the `project` arg, or the most recently updated repo the user can write to. */
37
+ async function pickProject(project) {
38
+ const projects = await (0, api_client_1.listProjects)();
39
+ if (project) {
40
+ const id = await (0, resolver_1.resolveProjectId)(project);
41
+ const found = projects.find((p) => p.id === id);
42
+ if (found && found.role && !WRITE_ROLES.has(found.role)) {
43
+ return `You have '${found.role}' access to '${found.name}' — saving needs editor or owner.`;
44
+ }
45
+ return found ?? { id, name: project };
46
+ }
47
+ const writable = projects.filter((p) => !p.role || WRITE_ROLES.has(p.role));
48
+ if (writable.length === 0) {
49
+ return `No repo you can save into. Create one at ${constants_1.API_BASE_URL}/dashboard, then call save_prompt again.`;
50
+ }
51
+ return writable[0];
52
+ }
53
+ async function savePromptFlow(args) {
54
+ const checked = (0, writeGuard_1.checkSaveInput)(args);
55
+ if (!checked.ok)
56
+ return { ok: false, message: checked.error };
57
+ const input = checked.value;
58
+ try {
59
+ const project = await pickProject(args.project);
60
+ if (typeof project === 'string')
61
+ return { ok: false, message: project };
62
+ // Idempotency: same title in the same repo → no duplicate.
63
+ const sameTitle = (await (0, api_client_1.listPrompts)({ search: input.title, projectId: project.id, limit: 100 })).filter((p) => p.title.trim().toLowerCase() === input.title.toLowerCase());
64
+ const identical = sameTitle.find((p) => (0, writeGuard_1.sameContent)((0, promptText_1.versionText)(p.current_version), input.content));
65
+ if (identical) {
66
+ return {
67
+ ok: true,
68
+ payload: {
69
+ status: 'unchanged',
70
+ message: 'Already saved with this exact content — nothing changed.',
71
+ id: identical.id,
72
+ title: identical.title,
73
+ repo: project.name,
74
+ version: identical.current_version?.version_number ?? null,
75
+ },
76
+ };
77
+ }
78
+ if (sameTitle.length > 0) {
79
+ return {
80
+ ok: false,
81
+ message: `A prompt titled '${sameTitle[0].title}' already exists in '${project.name}' with different content. ` +
82
+ 'Call update_prompt with that name to save this as a new version, or pick another title.',
83
+ payload: { id: sameTitle[0].id },
84
+ };
85
+ }
86
+ const saved = await (0, api_client_1.createPrompt)({
87
+ projectId: project.id,
88
+ title: input.title,
89
+ content: input.content,
90
+ description: input.description,
91
+ });
92
+ const tagged = [];
93
+ const tagsFailed = [];
94
+ for (const tag of input.tags) {
95
+ try {
96
+ await (0, api_client_1.addPromptTag)(saved.promptId, tag);
97
+ tagged.push(tag);
98
+ }
99
+ catch {
100
+ tagsFailed.push(tag);
101
+ }
102
+ }
103
+ const payload = {
104
+ status: 'created',
105
+ id: saved.promptId,
106
+ title: input.title,
107
+ repo: project.name,
108
+ version: saved.versionNumber ?? 1,
109
+ tags: tagged,
110
+ };
111
+ if (tagsFailed.length > 0)
112
+ payload.tags_failed = tagsFailed;
113
+ return { ok: true, payload };
114
+ }
115
+ catch (err) {
116
+ return { ok: false, message: describeWriteError(err) };
117
+ }
118
+ }
119
+ /** name is the prompt's id, short id (8+ hex prefix) or exact title (case-insensitive). */
120
+ function isExactReference(name, prompt) {
121
+ const n = name.trim().toLowerCase();
122
+ if (UUID_RE.test(n))
123
+ return prompt.id.toLowerCase() === n;
124
+ if (/^[0-9a-f]{8,}$/.test(n) && prompt.id.toLowerCase().startsWith(n))
125
+ return true;
126
+ return prompt.title.trim().toLowerCase() === n;
127
+ }
128
+ async function updatePromptFlow(args) {
129
+ const checked = (0, writeGuard_1.checkUpdateInput)(args);
130
+ if (!checked.ok)
131
+ return { ok: false, message: checked.error };
132
+ const { content, changelog } = checked.value;
133
+ try {
134
+ const projectId = args.project ? await (0, resolver_1.resolveProjectId)(args.project) : undefined;
135
+ const result = await (0, resolver_1.resolvePromptByName)(args.name, { projectId });
136
+ if (result.status === 'ambiguous') {
137
+ return {
138
+ ok: false,
139
+ message: `'${args.name}' matched several prompts. Call again with the exact title, an id, or the 'project' arg.`,
140
+ payload: { candidates: result.candidates },
141
+ };
142
+ }
143
+ if (result.status === 'not_found') {
144
+ return { ok: false, message: `No prompt matched '${args.name}'. To create it, call save_prompt.` };
145
+ }
146
+ const prompt = result.prompt;
147
+ if (!isExactReference(args.name, prompt)) {
148
+ return {
149
+ ok: false,
150
+ message: `'${args.name}' is not an exact title or id. Did you mean '${prompt.title}' (${prompt.id})? ` +
151
+ 'Call again with the exact title or id — updates never guess.',
152
+ };
153
+ }
154
+ const current = (0, promptText_1.pickVersion)(prompt);
155
+ if ((0, writeGuard_1.sameContent)((0, promptText_1.versionText)(current), content)) {
156
+ return {
157
+ ok: true,
158
+ payload: {
159
+ status: 'unchanged',
160
+ message: 'Content matches the current version — no new version created.',
161
+ id: prompt.id,
162
+ title: prompt.title,
163
+ version: current?.version_number ?? null,
164
+ },
165
+ };
166
+ }
167
+ const saved = await (0, api_client_1.savePromptVersion)({ promptId: prompt.id, content, changelog, bump: args.bump });
168
+ return {
169
+ ok: true,
170
+ payload: {
171
+ status: 'updated',
172
+ id: prompt.id,
173
+ title: prompt.title,
174
+ version: saved.versionNumber ?? null,
175
+ previous_version: current?.version_number ?? null,
176
+ note: 'The previous version is kept; roll back any time from the web or `ple rollback`.',
177
+ },
178
+ };
179
+ }
180
+ catch (err) {
181
+ return { ok: false, message: describeWriteError(err) };
182
+ }
183
+ }
package/dist/server.js CHANGED
@@ -3,14 +3,21 @@
3
3
  * promptlike-mcp sunucu kurulumu (transport'tan bağımsız → testte InMemory
4
4
  * transport'la, üretimde stdio ile bağlanır).
5
5
  *
6
- * İki yüzey:
7
- * - tools (v0.1+): list_prompts / search_prompts / get_prompt / fill_variables
6
+ * Üç yüzey:
7
+ * - tools: okuma (list_prompts / search_prompts / get_prompt / fill_variables
8
+ * / suggest_prompts) + yazma (v0.4+, W1-3: save_prompt / update_prompt)
8
9
  * - prompts (v0.3+): kullanıcının kütüphanesi MCP prompt'u olarak — istemcinin
9
- * `/` menüsünde görünür, {{değişkenler}} prompt argümanı olur.
10
- * İkisi de SALT-OKUNUR (REV-4 v1 kapsamı: yazma/improve yok).
10
+ * `/` menüsünde görünür, {{değişkenler}} prompt argümanı olur. Yerleşik
11
+ * `save-this` prompt'u (v0.4+) konuşmadaki talimatı kaydettirir.
12
+ * - resources (v0.4+): `promptlike://<repo>/<prompt>` — Claude Code'da @-mention.
13
+ *
14
+ * Yazma kimliği her zaman `ple login` oturumunun token'ıdır; plan limitleri ve
15
+ * yetki API'de zorlanır. Silme aracı YOK (eski versiyon asla silinmez).
16
+ * MCP sampling kullanılmaz (2026-07-28 spec'inde deprecated).
11
17
  */
12
18
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.PROMPT_CATALOG_MAX_PAGES = void 0;
19
+ exports.SAVE_THIS_PROMPT = exports.PROMPT_CATALOG_MAX_PAGES = void 0;
20
+ exports.renderSaveThis = renderSaveThis;
14
21
  exports.createServer = createServer;
15
22
  const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
16
23
  const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
@@ -21,12 +28,23 @@ const resolver_1 = require("./lib/resolver");
21
28
  const promptVariables_1 = require("./lib/promptVariables");
22
29
  const promptText_1 = require("./lib/promptText");
23
30
  const mcpPrompts_1 = require("./lib/mcpPrompts");
31
+ const resources_1 = require("./lib/resources");
32
+ const writeTools_1 = require("./lib/writeTools");
33
+ const writeGuard_1 = require("./lib/writeGuard");
24
34
  function ok(payload) {
25
35
  return { content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }] };
26
36
  }
27
37
  function fail(message) {
28
38
  return { content: [{ type: 'text', text: message }], isError: true };
29
39
  }
40
+ function fromOutcome(outcome) {
41
+ if (outcome.ok)
42
+ return ok(outcome.payload);
43
+ if (outcome.payload) {
44
+ return { content: [{ type: 'text', text: JSON.stringify({ error: outcome.message, ...outcome.payload }, null, 2) }], isError: true };
45
+ }
46
+ return fail(outcome.message);
47
+ }
30
48
  /** Tool gövdesi sarmalayıcı: auth guard + hataları temiz mesaja çevirir. */
31
49
  async function guarded(fn) {
32
50
  try {
@@ -64,6 +82,15 @@ exports.PROMPT_CATALOG_MAX_PAGES = 5;
64
82
  const PROMPT_CATALOG_PAGE_SIZE = 100;
65
83
  /** list → get arası aynı katalog kullanılsın; kütüphane değişikliği ≤30 sn'de yansır. */
66
84
  const PROMPT_CATALOG_TTL_MS = 30000;
85
+ /**
86
+ * 2026-07-28 spec (SEP-2549) önbellek ipucu: liste yanıtları `ttlMs` +
87
+ * `cacheScope` taşır. Kütüphane kullanıcıya özel → `private`. Eski istemciler
88
+ * bilinmeyen alanı yok sayar.
89
+ */
90
+ const CACHE_HINT = { ttlMs: PROMPT_CATALOG_TTL_MS, cacheScope: 'private' };
91
+ /** Sunucunun yerleşik prompt'u: konuşmadaki talimatı kütüphaneye kaydettirir. */
92
+ exports.SAVE_THIS_PROMPT = 'save-this';
93
+ const RESERVED_PROMPT_NAMES = new Set([exports.SAVE_THIS_PROMPT]);
67
94
  async function fetchAllPrompts() {
68
95
  const all = [];
69
96
  for (let page = 1; page <= exports.PROMPT_CATALOG_MAX_PAGES; page++) {
@@ -82,26 +109,78 @@ function createCatalogCache(now) {
82
109
  return cached.entries;
83
110
  }
84
111
  await (0, api_client_1.ensureAuthed)();
85
- const entries = (0, mcpPrompts_1.buildPromptCatalog)(await fetchAllPrompts());
112
+ const entries = (0, mcpPrompts_1.buildPromptCatalog)(await fetchAllPrompts(), RESERVED_PROMPT_NAMES);
86
113
  cached = { at: now(), entries };
87
114
  return entries;
88
115
  },
116
+ /** Yazmadan sonra: bir sonraki list/get taze kütüphaneyi görür. */
117
+ invalidate() {
118
+ cached = null;
119
+ },
120
+ /** Katalogda ada göre ara; yoksa (yeni prompt) bir kez taze liste. */
121
+ async find(match) {
122
+ return (await this.get()).find(match) ?? (await this.get(true)).find(match);
123
+ },
89
124
  };
90
125
  }
126
+ /** initialize'da istemcinin bildirdiği ad/sürüm → olay defterindeki `client`. */
127
+ function clientLabel(server) {
128
+ const info = server.server.getClientVersion();
129
+ if (!info?.name)
130
+ return undefined;
131
+ return info.version ? `${info.name}/${info.version}` : info.name;
132
+ }
133
+ function useOptions(server, surface, extra = {}) {
134
+ return { surface, client: clientLabel(server), ...extra };
135
+ }
91
136
  function toMcpError(err) {
92
137
  if (err instanceof types_js_1.McpError)
93
138
  return err;
94
139
  return new types_js_1.McpError(types_js_1.ErrorCode.InternalError, err instanceof Error ? err.message : 'Unexpected error.');
95
140
  }
96
- function registerPromptLibrary(server, now) {
97
- const catalog = createCatalogCache(now);
141
+ /** save-this: modele konuşmadaki yeniden kullanılabilir talimatı çıkarıp kaydettirir. */
142
+ function saveThisPrompt() {
143
+ return {
144
+ name: exports.SAVE_THIS_PROMPT,
145
+ title: 'Save this as a PromptLikeEngineer prompt',
146
+ description: 'Extract the reusable instruction from this conversation, mark {{variables}}, and save it to your library.',
147
+ arguments: [
148
+ { name: 'title', description: 'Title to use (optional — otherwise one is proposed)', required: false },
149
+ { name: 'project', description: 'Repo to save into (optional — default: your most recent repo)', required: false },
150
+ { name: 'focus', description: 'What to capture, if not obvious (optional)', required: false },
151
+ ],
152
+ };
153
+ }
154
+ function renderSaveThis(args) {
155
+ const title = args?.title?.trim();
156
+ const project = args?.project?.trim();
157
+ const focus = args?.focus?.trim();
158
+ const lines = [
159
+ 'Look back over this conversation and extract the reusable instruction worth keeping as a saved prompt — the part someone would run again on a different input, not the one-off details.',
160
+ '',
161
+ '1. Write it as a standalone prompt: imperative, self-contained, no references to "above" or to this chat.',
162
+ '2. Replace everything that changes between uses with {{snake_case}} variables (e.g. {{file}}, {{language}}, {{audience}}).',
163
+ '3. Never include secrets, API keys, tokens, passwords, personal data or private URLs — use a {{variable}} instead.',
164
+ `4. ${title ? `Use the title "${title}".` : 'Pick a short, specific title (at most 60 characters).'} Add a one-line description.`,
165
+ `5. Show the user the title, description and prompt, then call the promptlike save_prompt tool with title, content and description${project ? `, and project "${project}"` : ''}.`,
166
+ '6. If save_prompt says a prompt with that title already exists, ask the user whether to call update_prompt (adds a new version; nothing is deleted) or pick another title.',
167
+ ];
168
+ if (focus)
169
+ lines.splice(1, 0, '', `Focus on: ${focus}`);
170
+ return lines.join('\n');
171
+ }
172
+ function registerPromptLibrary(server, catalog) {
98
173
  // McpServer.registerPrompt statik kayıt içindir; kütüphane kullanıcıya göre
99
174
  // dinamik olduğundan handler'lar alttaki Server'a doğrudan bağlanır.
100
- server.server.registerCapabilities({ prompts: { listChanged: false } });
175
+ // listChanged: save_prompt/update_prompt sonrası istemciye bildirilir.
176
+ server.server.registerCapabilities({
177
+ prompts: { listChanged: true },
178
+ resources: { listChanged: true },
179
+ });
101
180
  server.server.setRequestHandler(types_js_1.ListPromptsRequestSchema, async () => {
102
181
  try {
103
182
  const entries = await catalog.get();
104
- return { prompts: entries.map(mcpPrompts_1.toMcpPrompt) };
183
+ return { prompts: [saveThisPrompt(), ...entries.map(mcpPrompts_1.toMcpPrompt)], ...CACHE_HINT };
105
184
  }
106
185
  catch (err) {
107
186
  throw toMcpError(err);
@@ -109,12 +188,15 @@ function registerPromptLibrary(server, now) {
109
188
  });
110
189
  server.server.setRequestHandler(types_js_1.GetPromptRequestSchema, async (request) => {
111
190
  const { name, arguments: args } = request.params;
191
+ if (name === exports.SAVE_THIS_PROMPT) {
192
+ return {
193
+ description: 'Save the reusable instruction from this conversation',
194
+ messages: [{ role: 'user', content: { type: 'text', text: renderSaveThis(args) } }],
195
+ };
196
+ }
112
197
  let entry;
113
198
  try {
114
- entry = (await catalog.get()).find((e) => e.name === name);
115
- // Önbellek bayat olabilir (yeni eklenen prompt) → bir kez taze liste.
116
- if (!entry)
117
- entry = (await catalog.get(true)).find((e) => e.name === name);
199
+ entry = await catalog.find((e) => e.name === name);
118
200
  }
119
201
  catch (err) {
120
202
  throw toMcpError(err);
@@ -132,8 +214,9 @@ function registerPromptLibrary(server, now) {
132
214
  if (!detail) {
133
215
  throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt '${name}' is no longer available.`);
134
216
  }
135
- const rendered = (0, mcpPrompts_1.renderPrompt)((0, promptText_1.versionText)((0, promptText_1.pickVersion)(detail)), args);
136
- (0, api_client_1.recordPromptUse)(detail.id);
217
+ const picked = (0, promptText_1.pickVersion)(detail);
218
+ const rendered = (0, mcpPrompts_1.renderPrompt)((0, promptText_1.versionText)(picked), args);
219
+ (0, api_client_1.recordPromptUse)(detail.id, useOptions(server, 'mcp_prompt', { version: picked?.version_number }));
137
220
  const description = rendered.missing.length > 0
138
221
  ? `${detail.title} — unfilled: ${rendered.missing.join(', ')}`
139
222
  : detail.title;
@@ -143,8 +226,71 @@ function registerPromptLibrary(server, now) {
143
226
  };
144
227
  });
145
228
  }
229
+ function registerResources(server, catalog) {
230
+ server.server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async () => {
231
+ try {
232
+ const entries = await catalog.get();
233
+ return { resources: entries.map(resources_1.toMcpResource), ...CACHE_HINT };
234
+ }
235
+ catch (err) {
236
+ throw toMcpError(err);
237
+ }
238
+ });
239
+ server.server.setRequestHandler(types_js_1.ListResourceTemplatesRequestSchema, async () => ({
240
+ resourceTemplates: [
241
+ {
242
+ uriTemplate: resources_1.RESOURCE_TEMPLATE,
243
+ name: 'prompt',
244
+ title: 'Saved prompt',
245
+ description: 'A prompt from your PromptLikeEngineer library (current version, as Markdown).',
246
+ mimeType: resources_1.RESOURCE_MIME,
247
+ },
248
+ ],
249
+ }));
250
+ server.server.setRequestHandler(types_js_1.ReadResourceRequestSchema, async (request) => {
251
+ const { uri } = request.params;
252
+ let entry;
253
+ try {
254
+ entry = await catalog.find((e) => (0, resources_1.findByUri)([e], uri) !== undefined);
255
+ }
256
+ catch (err) {
257
+ throw toMcpError(err);
258
+ }
259
+ if (!entry) {
260
+ throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Resource '${uri}' not found in your library.`);
261
+ }
262
+ let detail;
263
+ try {
264
+ detail = await (0, api_client_1.getPromptDetail)(entry.prompt.id);
265
+ }
266
+ catch (err) {
267
+ throw toMcpError(err);
268
+ }
269
+ if (!detail)
270
+ throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Resource '${uri}' is no longer available.`);
271
+ const picked = (0, promptText_1.pickVersion)(detail);
272
+ (0, api_client_1.recordPromptUse)(detail.id, useOptions(server, 'mcp_resource', { version: picked?.version_number }));
273
+ return {
274
+ contents: [{ uri, mimeType: resources_1.RESOURCE_MIME, text: (0, promptText_1.versionText)(picked) }],
275
+ ttlMs: PROMPT_CATALOG_TTL_MS,
276
+ cacheScope: 'private',
277
+ };
278
+ });
279
+ }
280
+ /** Yazma sonrası: önbelleği boşalt, istemciye liste değişti de (hata yutulur). */
281
+ function afterWrite(server, catalog) {
282
+ catalog.invalidate();
283
+ if (!server.isConnected())
284
+ return;
285
+ server.server.sendPromptListChanged().catch(() => undefined);
286
+ server.server.sendResourceListChanged().catch(() => undefined);
287
+ }
288
+ const READ_ONLY = { readOnlyHint: true, openWorldHint: false };
289
+ /** Yazma: yeni prompt/versiyon ekler, hiçbir şeyi silmez; aynı içerikle tekrar = no-op. */
290
+ const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };
146
291
  function createServer(options = {}) {
147
292
  const server = new mcp_js_1.McpServer({ name: constants_1.MCP_SERVER_NAME, version: constants_1.MCP_VERSION });
293
+ const catalog = createCatalogCache(options.now ?? Date.now);
148
294
  server.registerTool('list_prompts', {
149
295
  title: 'List prompts',
150
296
  description: "List the user's saved prompts from their PromptLikeEngineer library. " +
@@ -154,6 +300,7 @@ function createServer(options = {}) {
154
300
  tag: zod_1.z.string().optional().describe('Filter by tag name'),
155
301
  limit: zod_1.z.number().int().min(1).max(100).optional().describe('Max results (default 50)'),
156
302
  },
303
+ annotations: READ_ONLY,
157
304
  }, async ({ tag, limit }) => guarded(async () => {
158
305
  const prompts = await (0, api_client_1.listPrompts)({ tag, limit: limit ?? 50 });
159
306
  return ok({ total: prompts.length, prompts: prompts.map(summarize) });
@@ -166,6 +313,7 @@ function createServer(options = {}) {
166
313
  query: zod_1.z.string().min(1).describe('Search text (matched against title + description)'),
167
314
  limit: zod_1.z.number().int().min(1).max(100).optional().describe('Max results (default 20)'),
168
315
  },
316
+ annotations: READ_ONLY,
169
317
  }, async ({ query, limit }) => guarded(async () => {
170
318
  const prompts = await (0, api_client_1.listPrompts)({ search: query, limit: limit ?? 20 });
171
319
  return ok({ total: prompts.length, prompts: prompts.map(summarize) });
@@ -180,8 +328,13 @@ function createServer(options = {}) {
180
328
  name: zod_1.z.string().min(1).describe('Prompt title, id, or unique title fragment'),
181
329
  version: zod_1.z.number().int().min(1).optional().describe('Exact version number to fetch (default: current)'),
182
330
  project: zod_1.z.string().min(1).optional().describe('Repo name, slug, or id to scope resolution when titles collide'),
331
+ via: zod_1.z
332
+ .enum(['direct', 'suggestion'])
333
+ .optional()
334
+ .describe("Set 'suggestion' when fetching a prompt that suggest_prompts or a PromptLikeEngineer hint offered"),
183
335
  },
184
- }, async ({ name, version, project }) => guarded(async () => {
336
+ annotations: READ_ONLY,
337
+ }, async ({ name, version, project, via }) => guarded(async () => {
185
338
  const projectId = project ? await (0, resolver_1.resolveProjectId)(project) : undefined;
186
339
  const result = await (0, resolver_1.resolvePromptByName)(name, { projectId });
187
340
  if (result.status !== 'found')
@@ -193,7 +346,7 @@ function createServer(options = {}) {
193
346
  return fail(`Version ${version} not found for '${prompt.title}'. Available: ${available.join(', ') || 'none'}.`);
194
347
  }
195
348
  const text = (0, promptText_1.versionText)(picked);
196
- (0, api_client_1.recordPromptUse)(prompt.id);
349
+ (0, api_client_1.recordPromptUse)(prompt.id, useOptions(server, 'mcp_tool', { via, version: picked.version_number }));
197
350
  return ok({
198
351
  id: prompt.id,
199
352
  title: prompt.title,
@@ -215,6 +368,7 @@ function createServer(options = {}) {
215
368
  version: zod_1.z.number().int().min(1).optional().describe('Exact version number (default: current)'),
216
369
  project: zod_1.z.string().min(1).optional().describe('Repo name, slug, or id to scope resolution when titles collide'),
217
370
  },
371
+ annotations: READ_ONLY,
218
372
  }, async ({ name, variables, version, project }) => guarded(async () => {
219
373
  const projectId = project ? await (0, resolver_1.resolveProjectId)(project) : undefined;
220
374
  const result = await (0, resolver_1.resolvePromptByName)(name, { projectId });
@@ -229,7 +383,7 @@ function createServer(options = {}) {
229
383
  const raw = (0, promptText_1.versionText)(picked);
230
384
  const filled = (0, promptVariables_1.fillVariables)(raw, variables);
231
385
  const missing = (0, promptVariables_1.extractVariables)(filled);
232
- (0, api_client_1.recordPromptUse)(prompt.id);
386
+ (0, api_client_1.recordPromptUse)(prompt.id, useOptions(server, 'mcp_tool', { version: picked.version_number }));
233
387
  return ok({
234
388
  id: prompt.id,
235
389
  title: prompt.title,
@@ -238,6 +392,73 @@ function createServer(options = {}) {
238
392
  content: filled,
239
393
  });
240
394
  }));
241
- registerPromptLibrary(server, options.now ?? Date.now);
395
+ server.registerTool('suggest_prompts', {
396
+ title: 'Suggest saved prompts',
397
+ description: "Call once at the start of a non-trivial task to check the user's saved prompts. " +
398
+ 'Returns up to `limit` prompts from their own library that match the task (title/description ' +
399
+ "match, weighted by past use). If one fits, fetch it with get_prompt (via: 'suggestion'). " +
400
+ 'An empty list means nothing fits — carry on normally. The task text is not stored.',
401
+ inputSchema: {
402
+ task: zod_1.z.string().min(1).max(2000).describe("A short description of the user's task"),
403
+ limit: zod_1.z.number().int().min(1).max(10).optional().describe('Max suggestions (default 3)'),
404
+ },
405
+ annotations: READ_ONLY,
406
+ }, async ({ task, limit }) => guarded(async () => {
407
+ const found = await (0, api_client_1.suggestPrompts)(task, limit ?? 3);
408
+ if (found.length === 0) {
409
+ return ok({ suggestions: [], note: 'No saved prompt fits this task — continue normally.' });
410
+ }
411
+ return ok({
412
+ suggestions: found.map((s) => ({
413
+ id: s.id,
414
+ title: s.title,
415
+ description: s.description,
416
+ used: s.use_count,
417
+ score: s.score,
418
+ })),
419
+ next_step: "If one fits, call get_prompt with its id and via: 'suggestion'.",
420
+ });
421
+ }));
422
+ server.registerTool('save_prompt', {
423
+ title: 'Save a new prompt',
424
+ description: "Save a new prompt to the user's PromptLikeEngineer library (use when the user asks to keep/save " +
425
+ 'a prompt, or via the save-this prompt). Mark reusable parts as {{variables}}; never include secrets. ' +
426
+ 'Saving the same title + content again is a no-op. If the title already exists with different ' +
427
+ 'content, call update_prompt instead. Plan limits apply (the error says so).',
428
+ inputSchema: {
429
+ title: zod_1.z.string().min(1).max(writeGuard_1.MAX_TITLE).describe('Short, specific title'),
430
+ content: zod_1.z.string().min(1).max(writeGuard_1.MAX_CONTENT).describe('The prompt text; use {{variable}} placeholders'),
431
+ description: zod_1.z.string().max(writeGuard_1.MAX_DESCRIPTION).optional().describe('One-line description'),
432
+ project: zod_1.z.string().min(1).optional().describe('Repo name, slug, or id (default: most recently updated repo you can write to)'),
433
+ tags: zod_1.z.array(zod_1.z.string().min(1).max(writeGuard_1.MAX_TAG_LENGTH)).max(writeGuard_1.MAX_TAGS).optional().describe('Tag names'),
434
+ },
435
+ annotations: WRITE,
436
+ }, async (args) => guarded(async () => {
437
+ const outcome = await (0, writeTools_1.savePromptFlow)(args);
438
+ if (outcome.ok && outcome.payload.status === 'created')
439
+ afterWrite(server, catalog);
440
+ return fromOutcome(outcome);
441
+ }));
442
+ server.registerTool('update_prompt', {
443
+ title: 'Save a new version of a prompt',
444
+ description: 'Save new content for an existing prompt as a NEW version (the old version is kept; nothing is ' +
445
+ 'deleted). `name` must be the exact title or the id. Content equal to the current version creates ' +
446
+ "no version. bump: 'patch' (default), 'minor' or 'major'.",
447
+ inputSchema: {
448
+ name: zod_1.z.string().min(1).describe('Exact prompt title, or its id / short id'),
449
+ content: zod_1.z.string().min(1).max(writeGuard_1.MAX_CONTENT).describe('The full new prompt text'),
450
+ changelog: zod_1.z.string().max(500).optional().describe('What changed, one line'),
451
+ bump: zod_1.z.enum(['patch', 'minor', 'major']).optional().describe('Semver bump (default patch)'),
452
+ project: zod_1.z.string().min(1).optional().describe('Repo name, slug, or id when titles collide'),
453
+ },
454
+ annotations: WRITE,
455
+ }, async (args) => guarded(async () => {
456
+ const outcome = await (0, writeTools_1.updatePromptFlow)(args);
457
+ if (outcome.ok && outcome.payload.status === 'updated')
458
+ afterWrite(server, catalog);
459
+ return fromOutcome(outcome);
460
+ }));
461
+ registerPromptLibrary(server, catalog);
462
+ registerResources(server, catalog);
242
463
  return server;
243
464
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "promptlike-mcp",
3
- "version": "0.3.0",
4
- "mcpName": "io.github.zeynepaslierhann/promptlike-mcp",
5
- "description": "MCP server for PromptLikeEngineer - read-only access to your prompt library as MCP tools and slash-command prompts (list, search, get, fill {{variables}}).",
3
+ "version": "0.4.1",
4
+ "mcpName": "io.github.zeynepaslierhan/promptlike-mcp",
5
+ "description": "MCP server for PromptLikeEngineer - your prompt library as MCP tools, slash-command prompts and @-resources: list, search, get, fill {{variables}}, suggest, and save new prompts/versions (add-only).",
6
6
  "bin": {
7
7
  "promptlike-mcp": "dist/index.js",
8
8
  "ple-mcp": "dist/index.js"
@@ -18,6 +18,7 @@
18
18
  "dev": "tsc --watch",
19
19
  "typecheck": "tsc --noEmit",
20
20
  "test": "vitest run",
21
+ "e2e:stdio": "npm run build && node scripts/e2e-stdio.mjs",
21
22
  "start": "node dist/index.js",
22
23
  "clean": "rm -rf dist",
23
24
  "prepack": "npm run clean && npm run build"