promptlike-mcp 0.1.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.
package/README.md ADDED
@@ -0,0 +1,52 @@
1
+ # promptlike-mcp
2
+
3
+ MCP (Model Context Protocol) server for [PromptLikeEngineer](https://promptlikeengineer.com) — gives AI agents **read-only** access to your prompt library.
4
+
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
+
7
+ ## Setup
8
+
9
+ 1. Sign in once with the CLI (the MCP server shares its session — zero extra config):
10
+
11
+ ```bash
12
+ npm i -g promptlike
13
+ ple login
14
+ ```
15
+
16
+ 2. Add the server to your agent. Claude Code:
17
+
18
+ ```bash
19
+ claude mcp add promptlike -- npx -y promptlike-mcp
20
+ ```
21
+
22
+ Any other MCP client: run `npx -y promptlike-mcp` over stdio.
23
+
24
+ ## Tools (v1 — read-only)
25
+
26
+ | Tool | What it does |
27
+ |---|---|
28
+ | `list_prompts` | List your prompts (optional `tag` filter). Includes each prompt's `{{variable}}` names. |
29
+ | `search_prompts` | Search by title/description. |
30
+ | `get_prompt` | Full content by name/id/short-id, optional `version` pin. |
31
+ | `fill_variables` | Fetch + substitute `{{variables}}`, returns ready-to-use text (unfilled ones reported in `missing_variables`). |
32
+
33
+ Writing/improving prompts is intentionally out of scope in v1 — an agent can never burn your AI tokens or mutate your library through this server.
34
+
35
+ ## Notes
36
+
37
+ - Ambiguous names return a candidate list (id + title) — call again with a more specific name or the id.
38
+ - Rate limits surface as `Retry in Ns` messages so agents can back off.
39
+ - Self-hosters: point at another deployment with `PROMPTLIKE_API_URL` (same env var the CLI honors).
40
+ - Session store: `~/.config/promptlike/config.json` (written by `ple login`, file mode 0600).
41
+
42
+ ## Publishing (maintainers)
43
+
44
+ Same OIDC Trusted Publishing flow as the CLI — no npm token:
45
+
46
+ ```bash
47
+ npm --prefix mcp version patch --no-git-tag-version
48
+ git add mcp/package.json mcp/package-lock.json && git commit -m "mcp: vX.Y.Z"
49
+ git tag mcp-vX.Y.Z && git push origin main mcp-vX.Y.Z
50
+ ```
51
+
52
+ `.github/workflows/mcp-publish.yml` runs typecheck + tests + build, then publishes.
package/dist/index.js ADDED
@@ -0,0 +1,183 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * promptlike-mcp — PromptLikeEngineer MCP server (stdio).
5
+ *
6
+ * AI agent'lara prompt kütüphanesine SALT-OKUNUR erişim verir (REV-4 v1
7
+ * kapsamı: yazma/improve yok → agent'ın token yakma / veri bozma riski yok).
8
+ * Auth sıfır kurulum: CLI'ın `ple login` ile yazdığı
9
+ * ~/.config/promptlike/config.json paylaşılır.
10
+ *
11
+ * Kurulum (Claude Code):
12
+ * claude mcp add promptlike -- npx -y promptlike-mcp
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
16
+ const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
17
+ const zod_1 = require("zod");
18
+ const constants_1 = require("./lib/constants");
19
+ const api_client_1 = require("./lib/api-client");
20
+ const resolver_1 = require("./lib/resolver");
21
+ const promptVariables_1 = require("./lib/promptVariables");
22
+ function ok(payload) {
23
+ return { content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }] };
24
+ }
25
+ function fail(message) {
26
+ return { content: [{ type: 'text', text: message }], isError: true };
27
+ }
28
+ /** Tool gövdesi sarmalayıcı: auth guard + hataları temiz mesaja çevirir. */
29
+ async function guarded(fn) {
30
+ try {
31
+ await (0, api_client_1.ensureAuthed)();
32
+ return await fn();
33
+ }
34
+ catch (err) {
35
+ return fail(err instanceof Error ? err.message : 'Unexpected error.');
36
+ }
37
+ }
38
+ /** Bir versiyonun kopyalanabilir düz metni (legacy content → 3-part birleşim). */
39
+ function versionText(v) {
40
+ if (!v)
41
+ return '';
42
+ if (v.content)
43
+ return v.content;
44
+ const parts = [v.role_text, v.description_text, v.context_text].filter(Boolean);
45
+ return parts.join('\n\n---\n\n');
46
+ }
47
+ /** Ambiguous/not-found çözümleme sonuçlarını tool yanıtına çevirir. */
48
+ function resolveFailure(name, result) {
49
+ if (result.status === 'ambiguous') {
50
+ return ok({
51
+ error: `'${name}' matched multiple prompts. Call again with a more specific name or an id from the candidates.`,
52
+ candidates: result.candidates,
53
+ });
54
+ }
55
+ return fail(`No prompt matched '${name}'.`);
56
+ }
57
+ /** get_prompt / fill_variables ortak içerik seçimi (version pin dahil). */
58
+ function pickVersion(prompt, version) {
59
+ if (version === undefined)
60
+ return prompt.current_version ?? prompt.versions?.[0] ?? null;
61
+ return prompt.versions?.find((v) => v.version_number === version) ?? null;
62
+ }
63
+ // ---------------------------------------------------------------------------
64
+ // Server + tools
65
+ // ---------------------------------------------------------------------------
66
+ const server = new mcp_js_1.McpServer({ name: constants_1.MCP_SERVER_NAME, version: constants_1.MCP_VERSION });
67
+ server.registerTool('list_prompts', {
68
+ title: 'List prompts',
69
+ description: "List the user's saved prompts from their PromptLikeEngineer library. " +
70
+ 'Optionally filter by tag. Returns id, title, description, updated_at and ' +
71
+ 'the {{variable}} names each prompt expects.',
72
+ inputSchema: {
73
+ tag: zod_1.z.string().optional().describe('Filter by tag name'),
74
+ limit: zod_1.z.number().int().min(1).max(100).optional().describe('Max results (default 50)'),
75
+ },
76
+ }, async ({ tag, limit }) => guarded(async () => {
77
+ const prompts = await (0, api_client_1.listPrompts)({ tag, limit: limit ?? 50 });
78
+ return ok({
79
+ total: prompts.length,
80
+ prompts: prompts.map((p) => ({
81
+ id: p.id,
82
+ title: p.title,
83
+ description: p.description ?? null,
84
+ updated_at: p.updated_at,
85
+ variables: (0, promptVariables_1.extractVariables)(versionText(p.current_version)),
86
+ })),
87
+ });
88
+ }));
89
+ server.registerTool('search_prompts', {
90
+ title: 'Search prompts',
91
+ description: "Search the user's prompt library by title and description. " +
92
+ 'Returns the same shape as list_prompts.',
93
+ inputSchema: {
94
+ query: zod_1.z.string().min(1).describe('Search text (matched against title + description)'),
95
+ limit: zod_1.z.number().int().min(1).max(100).optional().describe('Max results (default 20)'),
96
+ },
97
+ }, async ({ query, limit }) => guarded(async () => {
98
+ const prompts = await (0, api_client_1.listPrompts)({ search: query, limit: limit ?? 20 });
99
+ return ok({
100
+ total: prompts.length,
101
+ prompts: prompts.map((p) => ({
102
+ id: p.id,
103
+ title: p.title,
104
+ description: p.description ?? null,
105
+ updated_at: p.updated_at,
106
+ variables: (0, promptVariables_1.extractVariables)(versionText(p.current_version)),
107
+ })),
108
+ });
109
+ }));
110
+ server.registerTool('get_prompt', {
111
+ title: 'Get prompt content',
112
+ description: 'Fetch the full content of one prompt by name, title, id or short-id. ' +
113
+ 'Optionally pin an exact version number. Returns the prompt text plus the ' +
114
+ '{{variable}} names it expects — if there are variables, either fill them ' +
115
+ 'yourself or call fill_variables.',
116
+ inputSchema: {
117
+ name: zod_1.z.string().min(1).describe('Prompt title, id, or unique title fragment'),
118
+ version: zod_1.z.number().int().min(1).optional().describe('Exact version number to fetch (default: current)'),
119
+ },
120
+ }, async ({ name, version }) => guarded(async () => {
121
+ const result = await (0, resolver_1.resolvePromptByName)(name);
122
+ if (result.status !== 'found')
123
+ return resolveFailure(name, result);
124
+ const prompt = result.prompt;
125
+ const picked = pickVersion(prompt, version);
126
+ if (!picked) {
127
+ const available = (prompt.versions ?? []).map((v) => v.version_number);
128
+ return fail(`Version ${version} not found for '${prompt.title}'. Available: ${available.join(', ') || 'none'}.`);
129
+ }
130
+ const text = versionText(picked);
131
+ (0, api_client_1.recordPromptUse)(prompt.id);
132
+ return ok({
133
+ id: prompt.id,
134
+ title: prompt.title,
135
+ description: prompt.description ?? null,
136
+ version: picked.version_number ?? null,
137
+ updated_at: prompt.updated_at,
138
+ variables: (0, promptVariables_1.extractVariables)(text),
139
+ content: text,
140
+ });
141
+ }));
142
+ server.registerTool('fill_variables', {
143
+ title: 'Fill prompt variables',
144
+ description: 'Fetch a prompt and substitute its {{variable}} placeholders with the given ' +
145
+ 'values, returning ready-to-use text. Unknown/empty values stay as {{name}} ' +
146
+ 'in the output (listed in missing_variables).',
147
+ inputSchema: {
148
+ name: zod_1.z.string().min(1).describe('Prompt title, id, or unique title fragment'),
149
+ variables: zod_1.z.record(zod_1.z.string()).describe('Variable name → value map'),
150
+ version: zod_1.z.number().int().min(1).optional().describe('Exact version number (default: current)'),
151
+ },
152
+ }, async ({ name, variables, version }) => guarded(async () => {
153
+ const result = await (0, resolver_1.resolvePromptByName)(name);
154
+ if (result.status !== 'found')
155
+ return resolveFailure(name, result);
156
+ const prompt = result.prompt;
157
+ const picked = pickVersion(prompt, version);
158
+ if (!picked) {
159
+ const available = (prompt.versions ?? []).map((v) => v.version_number);
160
+ return fail(`Version ${version} not found for '${prompt.title}'. Available: ${available.join(', ') || 'none'}.`);
161
+ }
162
+ const raw = versionText(picked);
163
+ const filled = (0, promptVariables_1.fillVariables)(raw, variables);
164
+ const missing = (0, promptVariables_1.extractVariables)(filled);
165
+ (0, api_client_1.recordPromptUse)(prompt.id);
166
+ return ok({
167
+ id: prompt.id,
168
+ title: prompt.title,
169
+ version: picked.version_number ?? null,
170
+ missing_variables: missing,
171
+ content: filled,
172
+ });
173
+ }));
174
+ async function main() {
175
+ const transport = new stdio_js_1.StdioServerTransport();
176
+ await server.connect(transport);
177
+ // stdio sunucusunda stdout PROTOKOLE ait — insan-log'u stderr'e.
178
+ console.error(`promptlike-mcp v${constants_1.MCP_VERSION} ready (stdio).`);
179
+ }
180
+ main().catch((err) => {
181
+ console.error('Fatal:', err instanceof Error ? err.message : err);
182
+ process.exit(1);
183
+ });
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ /**
3
+ * Thin HTTP client for the PromptLikeEngineer web API — MCP kopyası.
4
+ *
5
+ * `cli/src/lib/api-client.ts` ile aynı davranış sözleşmesi (CLI npm paketi
6
+ * internals export etmediği için kopya; emsal: promptVariables). Farklar:
7
+ * - login YOK — MCP kendisi oturum açmaz, CLI'ın `ple login` ile yazdığı
8
+ * ~/.config/promptlike/config.json paylaşılır (sıfır kurulum).
9
+ * - X-Client-Version header'ı `mcp/<sürüm>` gönderir.
10
+ *
11
+ * Sorumluluklar: bearer token ekleme, proaktif + reaktif (401→tek retry)
12
+ * refresh, 429/hata gövdelerini temiz mesajlara map'leme.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.NOT_LOGGED_IN = void 0;
16
+ exports.ensureAuthed = ensureAuthed;
17
+ exports.listPrompts = listPrompts;
18
+ exports.getPromptDetail = getPromptDetail;
19
+ exports.recordPromptUse = recordPromptUse;
20
+ const constants_1 = require("./constants");
21
+ const config_1 = require("./config");
22
+ exports.NOT_LOGGED_IN = 'Not logged in. Run `ple login` in a terminal first (install: npm i -g promptlike).';
23
+ const SESSION_EXPIRED = 'Session expired. Run `ple login` in a terminal to sign in again.';
24
+ function buildUrl(path, query) {
25
+ const u = new URL(constants_1.API_BASE_URL + path);
26
+ if (query) {
27
+ for (const [key, value] of Object.entries(query)) {
28
+ if (value !== undefined && value !== '') {
29
+ u.searchParams.set(key, String(value));
30
+ }
31
+ }
32
+ }
33
+ return u.toString();
34
+ }
35
+ async function toError(res) {
36
+ let body = {};
37
+ try {
38
+ body = (await res.json());
39
+ }
40
+ catch {
41
+ // Non-JSON error body — generic message below.
42
+ }
43
+ if (body.error)
44
+ return new Error(body.error);
45
+ return new Error(`Request failed (${res.status}).`);
46
+ }
47
+ function getAccessTokenOrThrow() {
48
+ const config = (0, config_1.readConfig)();
49
+ if (!config)
50
+ throw new Error(exports.NOT_LOGGED_IN);
51
+ return config.access_token;
52
+ }
53
+ function persist(data) {
54
+ const previous = (0, config_1.readConfig)();
55
+ const config = {
56
+ access_token: data.access_token,
57
+ refresh_token: data.refresh_token,
58
+ email: data.user?.email ?? previous?.email ?? '',
59
+ user_id: data.user?.id ?? previous?.user_id ?? '',
60
+ expires_at: data.expires_at ?? Math.floor(Date.now() / 1000) + 3600,
61
+ };
62
+ (0, config_1.writeConfig)(config);
63
+ return config;
64
+ }
65
+ async function refreshSession() {
66
+ const config = (0, config_1.readConfig)();
67
+ if (!config)
68
+ throw new Error(exports.NOT_LOGGED_IN);
69
+ let data;
70
+ try {
71
+ data = await apiFetch('/api/auth/cli/refresh', {
72
+ method: 'POST',
73
+ body: { refresh_token: config.refresh_token },
74
+ auth: false,
75
+ });
76
+ }
77
+ catch {
78
+ throw new Error(SESSION_EXPIRED);
79
+ }
80
+ persist(data);
81
+ }
82
+ async function apiFetch(path, opts = {}) {
83
+ const { method = 'GET', body, query, auth = true } = opts;
84
+ const headers = {
85
+ 'Content-Type': 'application/json',
86
+ 'X-Client-Version': `mcp/${constants_1.MCP_VERSION}`,
87
+ };
88
+ if (auth) {
89
+ headers['Authorization'] = `Bearer ${getAccessTokenOrThrow()}`;
90
+ }
91
+ let res;
92
+ try {
93
+ res = await fetch(buildUrl(path, query), {
94
+ method,
95
+ headers,
96
+ body: body === undefined ? undefined : JSON.stringify(body),
97
+ });
98
+ }
99
+ catch (err) {
100
+ throw new Error(`Cannot reach ${constants_1.API_BASE_URL}. Check your connection. (${err instanceof Error ? err.message : String(err)})`);
101
+ }
102
+ if (res.status === 401 && auth) {
103
+ if (opts._retried)
104
+ throw new Error(SESSION_EXPIRED);
105
+ await refreshSession();
106
+ return apiFetch(path, { ...opts, _retried: true });
107
+ }
108
+ if (res.status === 429) {
109
+ const retryAfter = res.headers.get('retry-after');
110
+ // Agent'lar back-off yapabilsin diye süre mesajda açık.
111
+ throw new Error(`Rate limited. Retry in ${retryAfter ? `${retryAfter}s` : 'a few seconds'}.`);
112
+ }
113
+ if (!res.ok) {
114
+ throw await toError(res);
115
+ }
116
+ return (await res.json());
117
+ }
118
+ // ---------------------------------------------------------------------------
119
+ // Public surface used by the tools / resolver
120
+ // ---------------------------------------------------------------------------
121
+ /**
122
+ * Guard for tool calls: throws the "run `ple login`" message when no session
123
+ * exists, and proactively refreshes a soon-to-expire token.
124
+ */
125
+ async function ensureAuthed() {
126
+ const config = (0, config_1.readConfig)();
127
+ if (!config)
128
+ throw new Error(exports.NOT_LOGGED_IN);
129
+ if ((0, config_1.isTokenExpiringSoon)(config)) {
130
+ await refreshSession();
131
+ }
132
+ }
133
+ /** GET /api/prompts — list the user's prompts (optionally by tag / search). */
134
+ async function listPrompts(params = {}) {
135
+ const res = await apiFetch('/api/prompts', {
136
+ query: {
137
+ tag: params.tag,
138
+ search: params.search,
139
+ limit: params.limit,
140
+ page: params.page,
141
+ },
142
+ });
143
+ return res.prompts ?? [];
144
+ }
145
+ /** GET /api/prompts/{id} — full detail incl. versions; null when 404. */
146
+ async function getPromptDetail(id) {
147
+ try {
148
+ const res = await apiFetch(`/api/prompts/${id}`);
149
+ return res.prompt ?? null;
150
+ }
151
+ catch (err) {
152
+ if (err instanceof Error && /not found/i.test(err.message))
153
+ return null;
154
+ throw err;
155
+ }
156
+ }
157
+ /**
158
+ * Kullanım kaydı — get_prompt/fill_variables sonrası fire-and-forget
159
+ * (CLI copy/get/show ile aynı desen). Hata YUTULUR.
160
+ */
161
+ function recordPromptUse(promptId) {
162
+ apiFetch(`/api/prompts/${promptId}/use`, { method: 'POST' }).catch(() => {
163
+ /* sessiz — telemetri */
164
+ });
165
+ }
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.getConfigPath = getConfigPath;
37
+ exports.readConfig = readConfig;
38
+ exports.writeConfig = writeConfig;
39
+ exports.clearConfig = clearConfig;
40
+ exports.isTokenExpiringSoon = isTokenExpiringSoon;
41
+ const fs = __importStar(require("fs"));
42
+ const os = __importStar(require("os"));
43
+ const path = __importStar(require("path"));
44
+ const CONFIG_DIR = path.join(os.homedir(), '.config', 'promptlike');
45
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
46
+ /** Config dosyasının tam yolu — debug çıktılarında göstermek için. */
47
+ function getConfigPath() {
48
+ return CONFIG_FILE;
49
+ }
50
+ /**
51
+ * Config'i diskten oku. Yoksa null döner — login gerekli demektir.
52
+ * Bozuk JSON varsa null döner ve dosyayı silmiyoruz; kullanıcı `ple logout`
53
+ * çağırsın diye log'ı sessiz tutuyoruz.
54
+ */
55
+ function readConfig() {
56
+ try {
57
+ if (!fs.existsSync(CONFIG_FILE))
58
+ return null;
59
+ const raw = fs.readFileSync(CONFIG_FILE, 'utf-8');
60
+ const parsed = JSON.parse(raw);
61
+ if (!parsed.access_token || !parsed.refresh_token)
62
+ return null;
63
+ return parsed;
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ }
69
+ /**
70
+ * Config'i diske yaz. Klasör yoksa oluştur, dosya izinlerini 0600 yap
71
+ * (sadece kullanıcı okuyabilir — token sızıntısı önlemi).
72
+ */
73
+ function writeConfig(config) {
74
+ if (!fs.existsSync(CONFIG_DIR)) {
75
+ fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
76
+ }
77
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), {
78
+ mode: 0o600,
79
+ });
80
+ }
81
+ /** `ple logout` için: config dosyasını ve klasörünü sil. */
82
+ function clearConfig() {
83
+ if (fs.existsSync(CONFIG_FILE)) {
84
+ fs.unlinkSync(CONFIG_FILE);
85
+ }
86
+ }
87
+ /** Token'ın 60 saniye içinde sona erecek olup olmadığını kontrol et. */
88
+ function isTokenExpiringSoon(config) {
89
+ const now = Math.floor(Date.now() / 1000);
90
+ return config.expires_at - now < 60;
91
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ /**
3
+ * MCP server configuration constants.
4
+ *
5
+ * The server talks to the PromptLikeEngineer **web API** (not Supabase),
6
+ * so it needs only a base URL — a public, non-secret value. Self-hosters can
7
+ * point it at another deployment via `PROMPTLIKE_API_URL` (same env var the
8
+ * CLI honors, so one export covers both tools).
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.MCP_VERSION = exports.MCP_SERVER_NAME = exports.API_BASE_URL = void 0;
12
+ const BAKED_API_URL = 'https://promptlikeengineer.com';
13
+ function resolveEnv(key, fallback) {
14
+ const value = process.env[key];
15
+ if (typeof value === 'string' && value.trim().length > 0) {
16
+ return value.trim();
17
+ }
18
+ return fallback;
19
+ }
20
+ /** Base URL of the web API (no trailing slash). */
21
+ exports.API_BASE_URL = resolveEnv('PROMPTLIKE_API_URL', BAKED_API_URL).replace(/\/+$/, '');
22
+ exports.MCP_SERVER_NAME = 'promptlike';
23
+ exports.MCP_VERSION = '0.1.0';
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ /**
3
+ * Prompt değişkenleri (`{{ad}}`) — CLI yerel kopyası.
4
+ *
5
+ * Web tarafındaki `src/lib/prompt-variables.ts` ile BİREBİR aynı mantık. CLI
6
+ * ayrı bir npm paketi olduğu için web'den import edemiyor; bu yüzden küçük,
7
+ * bağımlılıksız util burada tekrarlanıyor. Birini değiştirirken diğerini de
8
+ * güncelle (ya da ileride shared/ altına taşıyıp sync-types ile senkronla).
9
+ *
10
+ * Syntax: `{{ad}}`, içeride whitespace tolere, Unicode adlar (Türkçe dahil).
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.extractVariables = extractVariables;
14
+ exports.fillVariables = fillVariables;
15
+ const VARIABLE_PATTERN = /\{\{\s*([\p{L}\p{N}_.-]+)\s*\}\}/gu;
16
+ /** Metindeki benzersiz değişken adları, ilk görülme sırasıyla. */
17
+ function extractVariables(text) {
18
+ if (!text)
19
+ return [];
20
+ const seen = new Set();
21
+ const result = [];
22
+ for (const match of text.matchAll(VARIABLE_PATTERN)) {
23
+ const name = match[1];
24
+ if (!seen.has(name)) {
25
+ seen.add(name);
26
+ result.push(name);
27
+ }
28
+ }
29
+ return result;
30
+ }
31
+ /**
32
+ * `{{ad}}` yer tutucularını doldurur. Bulunmayan/boş değer çıktıda `{{ad}}`
33
+ * olarak kalır (sessizce silinmez).
34
+ */
35
+ function fillVariables(text, values) {
36
+ if (!text)
37
+ return '';
38
+ return text.replace(VARIABLE_PATTERN, (whole, name) => {
39
+ const value = values[name];
40
+ return value !== undefined && value !== '' ? value : whole;
41
+ });
42
+ }
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ /**
3
+ * İsim → prompt çözümleme — MCP uyarlaması.
4
+ *
5
+ * CLI `promptResolver.ts` ile aynı sıra: UUID → short-id prefix → başlık
6
+ * araması. Fark: belirsizlikte console'a yazmak yerine aday listesi DÖNER —
7
+ * agent kendisi seçip daha spesifik bir adla tekrar çağırır.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.resolvePromptByName = resolvePromptByName;
11
+ const api_client_1 = require("./api-client");
12
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
13
+ const SHORT_ID_RE = /^[0-9a-f]{8,}$/i;
14
+ function toCandidates(rows) {
15
+ return rows.slice(0, 10).map((r) => ({ id: r.id, title: r.title, updated_at: r.updated_at }));
16
+ }
17
+ /** Bulunan liste öğesini detail'e (versiyonlar dahil) yükselt. */
18
+ async function hydrate(row) {
19
+ const detail = await (0, api_client_1.getPromptDetail)(row.id);
20
+ if (!detail)
21
+ return { status: 'not_found' };
22
+ return { status: 'found', prompt: detail };
23
+ }
24
+ async function resolvePromptByName(name) {
25
+ const trimmed = name.trim();
26
+ if (!trimmed) {
27
+ throw new Error('Cannot resolve an empty name.');
28
+ }
29
+ // 1) Full UUID → detail endpoint.
30
+ if (UUID_RE.test(trimmed)) {
31
+ const found = await (0, api_client_1.getPromptDetail)(trimmed);
32
+ if (found)
33
+ return { status: 'found', prompt: found };
34
+ // Not found by id — fall through to a title search.
35
+ }
36
+ // 2) Short-id prefix (hex, 8+ chars, not a full UUID) → match a page.
37
+ if (!UUID_RE.test(trimmed) && SHORT_ID_RE.test(trimmed)) {
38
+ const page = await (0, api_client_1.listPrompts)({ limit: 100 });
39
+ const lower = trimmed.toLowerCase();
40
+ const matches = page.filter((p) => p.id.toLowerCase().startsWith(lower));
41
+ if (matches.length === 1)
42
+ return hydrate(matches[0]);
43
+ if (matches.length > 1)
44
+ return { status: 'ambiguous', candidates: toCandidates(matches) };
45
+ // No id match — fall through to a title search.
46
+ }
47
+ // 3) Title / description search.
48
+ const results = await (0, api_client_1.listPrompts)({ search: trimmed, limit: 100 });
49
+ const lower = trimmed.toLowerCase();
50
+ const titleMatches = results.filter((p) => p.title.toLowerCase().includes(lower));
51
+ const pool = titleMatches.length > 0 ? titleMatches : results;
52
+ if (pool.length === 0)
53
+ return { status: 'not_found' };
54
+ if (pool.length === 1)
55
+ return hydrate(pool[0]);
56
+ // Disambiguate on an exact (case-insensitive) title match if unique.
57
+ const exact = pool.filter((p) => p.title.toLowerCase() === lower);
58
+ if (exact.length === 1)
59
+ return hydrate(exact[0]);
60
+ return { status: 'ambiguous', candidates: toCandidates(pool) };
61
+ }
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "promptlike-mcp",
3
+ "version": "0.1.0",
4
+ "description": "MCP server for PromptLikeEngineer - gives AI agents read-only access to your prompt library (list, search, get, fill variables).",
5
+ "bin": {
6
+ "promptlike-mcp": "dist/index.js",
7
+ "ple-mcp": "dist/index.js"
8
+ },
9
+ "main": "./dist/index.js",
10
+ "files": [
11
+ "dist",
12
+ "README.md"
13
+ ],
14
+ "scripts": {
15
+ "build": "tsc && chmod +x dist/index.js",
16
+ "dev": "tsc --watch",
17
+ "typecheck": "tsc --noEmit",
18
+ "test": "vitest run",
19
+ "start": "node dist/index.js",
20
+ "clean": "rm -rf dist",
21
+ "prepack": "npm run clean && npm run build"
22
+ },
23
+ "keywords": [
24
+ "mcp",
25
+ "model-context-protocol",
26
+ "prompt",
27
+ "prompt-engineering",
28
+ "prompt-library",
29
+ "ai",
30
+ "llm",
31
+ "claude",
32
+ "agent",
33
+ "developer-tools"
34
+ ],
35
+ "author": {
36
+ "name": "Zeynep Aslı Erhan",
37
+ "url": "https://promptlikeengineer.com"
38
+ },
39
+ "license": "MIT",
40
+ "homepage": "https://promptlikeengineer.com",
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "engines": {
45
+ "node": ">=18"
46
+ },
47
+ "dependencies": {
48
+ "@modelcontextprotocol/sdk": "^1.12.0",
49
+ "zod": "^3.24.0"
50
+ },
51
+ "devDependencies": {
52
+ "@types/node": "^20.10.0",
53
+ "typescript": "^5.3.0",
54
+ "vitest": "^4.1.9"
55
+ }
56
+ }