promptlike-mcp 0.2.1 → 0.4.0

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.
@@ -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
+ }