#!/usr/bin/env node /** * youtrack — MCP-Server fuer die jetbrains/youtrack-Instanz (http://YOUR_SERVER_IP:8089). * * Sicherheitsmodell: * - Feste Basis-URL aus YOUTRACK_URL (kein Host/Port aus Tool-Eingaben -> kein SSRF). * - Permanent-Token kommt aus einer Datei (YOUTRACK_TOKEN_FILE, uid 1000, Modus 600), * nie aus dem Config-Text; wird nie geloggt. * - Suchen und Einzelzugriffe mit expliziten Feldern, um Riesenantworten zu vermeiden; * Texte auf MAX_CHARS begrenzt, Timeouts hart. */ 'use strict'; const http = require('http'); const fs = require('fs'); const TIMEOUT_MS = 8000; const MAX_CHARS = 60000; const YT_BASE = process.env.YOUTRACK_URL || 'http://YOUR_SERVER_IP:8089'; const INT_NAMES = [...new Set(['Type', 'Priority', 'State', 'Assignee', 'Subsystem', 'Fix versions', 'Affected versions'])]; const DEFAULT_TYPES = { Type: 'SingleEnumIssueCustomField', Priority: 'SingleEnumIssueCustomField', State: 'StateIssueCustomField', Assignee: 'SingleUserIssueCustomField', }; function readYoutrackToken() { const p = process.env.YOUTRACK_TOKEN_FILE; if (!p) return { error: 'YOUTRACK_TOKEN_FILE ist nicht gesetzt.' }; let st; try { st = fs.statSync(p); } catch (e) { return { error: `Token-Datei nicht lesbar: ${p}` }; } if ((st.mode & 0o077) !== 0) return { error: `Token-Datei ist nicht restriktiv berechtigt (Modus ${st.mode & 0o777}).` }; if (st.uid !== 1000) return { error: `Token-Datei gehoert uid ${st.uid}, erwartet 1000.` }; try { const t = fs.readFileSync(p, 'utf8').trim(); if (!t) return { error: 'Token-Datei ist leer.' }; return { token: t }; } catch (e) { return { error: 'Token-Datei konnte nicht gelesen werden.' }; } } function request(path, token, options) { return new Promise((resolve) => { const started = Date.now(); const method = (options && options.method) || 'GET'; const body = options && options.body; const headers = { Authorization: `Bearer ${token}`, ...(body ? { 'Content-Type': 'application/json' } : {}) }; const req = http.request(YT_BASE + path, { timeout: TIMEOUT_MS, method, headers }, (res) => { let data = ''; let done = false; const finish = () => { if (done) return; done = true; let parsed = null; let parseError = null; if (data) { try { parsed = JSON.parse(data); } catch (e) { parseError = 'Antwort ist kein JSON'; } } resolve({ code: res.statusCode || 0, ms: Date.now() - started, parsed, parseError, body: data.slice(0, MAX_CHARS) }); }; res.on('data', (d) => { data += d; if (data.length > MAX_CHARS * 2) { res.destroy(); finish(); } }); res.on('end', finish); res.on('close', finish); res.on('error', finish); }); req.on('timeout', () => { req.destroy(); resolve({ code: 0, ms: Date.now() - started, parsed: null, parseError: 'timeout' }); }); req.on('error', (e) => resolve({ code: 0, ms: Date.now() - started, parsed: null, parseError: String(e.message || e) })); if (body) req.write(JSON.stringify(body)); req.end(); }); } function apiError(r, fallback) { let desc = fallback; if (r.parsed && typeof r.parsed === 'object') { const e = []; if (r.parsed.error_description || r.parsed.error) e.push(String(r.parsed.error_description || r.parsed.error)); if (r.parsed.error_field) e.push(`Feld: ${r.parsed.error_field}`); if (e.length) desc = e.join('; '); } if (!desc && r.parseError) desc = r.parseError; return desc; } const TOOLS = [ { name: 'me', description: 'Identitaet und Eigenschaften des YouTrack-Accounts, mit dem Jarvis zugreift (Login, Name, E-Mail, ob Gast). Lesend.', inputSchema: { type: 'object', properties: {}, additionalProperties: false }, }, { name: 'list_projects', description: 'Listet alle sichtbaren YouTrack-Projekte (Kurzname + Anzeigename). Lesend.', inputSchema: { type: 'object', properties: {}, additionalProperties: false }, }, { name: 'search_issues', description: 'Durchsucht YouTrack mit der nativen Suchsyntax (z.B. "projekt PDEVHDI", "assignee: mich", "Diskuze: tasks", "erstellt: d-7d"). Liefert eine Tabelle mit Kurz-ID, Projekt und (offen/erledigt) und Zusammenfassung.', inputSchema: { type: 'object', properties: { query: { type: 'string', description: 'YouTrack-Suchabfrage. Leer = alle sichtbaren Issues.' }, max: { type: 'integer', description: 'Maximale Anzahl Treffer (1-50, Standard 10).' }, }, additionalProperties: false, }, }, { name: 'get_issue', description: 'Liefert ein einzelnes YouTrack-Issue mit Zusammenfassung, Beschreibung, Reporter, angepassten Feldern (Typ/Status/Prioritaet/…) und optionalen Kommentaren. Lesend.', inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'Kurz-ID, z.B. PDEVHDI-3.' }, include_comments: { type: 'boolean', description: 'Kommentare mit ausgeben (Standard: false).' }, }, required: ['id'], additionalProperties: false, }, }, { name: 'create_issue', description: 'Legt ein neues YouTrack-Issue an. Erforderlich: Projekt-Kurzname und Zusammenfassung. Optionale anpassbare Felder als Liste {"name":"Type","value":"Task"} u.ae. (Werte finden sich via get_issue an einem bestehenden Issue des Projekts). Liefert die neue Kurz-ID.', inputSchema: { type: 'object', properties: { project: { type: 'string', description: 'Projekt-Kurzname, z.B. PDEVHDI.' }, summary: { type: 'string', description: 'Titel des Issues.' }, description: { type: 'string', description: 'Details/Markdown.' }, custom_fields: { type: 'array', items: { type: 'object', properties: { name: { type: 'string', description: 'Feldname, z.B. Type, State, Priority, Assignee.' }, value: { description: 'Feldwert: Enum-Name als String oder Objekt (z.B. {"id":"…"}).' }, }, required: ['name', 'value'], additionalProperties: false, }, }, }, required: ['project', 'summary'], additionalProperties: false, }, }, { name: 'add_comment', description: 'Fuegt einem YouTrack-Issue einen Kommentar hinzu (z.B. Monitoring-Erkenntnisse). Liefert Kommentar-IDs/Bestatigung.', inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'Kurz-ID, z.B. PDEVHDI-3.' }, text: { type: 'string', description: 'Kommentartext (Markdown moeglich).' }, }, required: ['id', 'text'], additionalProperties: false, }, }, { name: 'update_issue_fields', description: 'Aendert anpassbare Felder eines bestehenden YouTrack-Issues, z.B. State auf "Solved" (Status/State Bundle), Assignee, Priority. Liefert den neuen Feldzustand.', inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'Kurz-ID, z.B. PDEVHDI-3.' }, custom_fields: { type: 'array', items: { type: 'object', properties: { name: { type: 'string', description: 'Feldname, z.B. State, Assignee, Priority.' }, value: { description: 'Feldwert: Enum-Name als String oder Objekt.' }, }, required: ['name', 'value'], additionalProperties: false, }, }, }, required: ['id', 'custom_fields'], additionalProperties: false, }, }, ]; function fmtValue(v) { if (v === null || v === undefined) return '-'; if (typeof v === 'boolean') return v ? 'ja' : 'nein'; if (typeof v === 'object') { if (v.name) return String(v.name); if (v.login) return String(v.login); if (v.seconds !== undefined) return Math.round(v.seconds / 3600) + ' h'; try { return JSON.stringify(v); } catch (e) { return '?'; } } return String(v); } async function me() { const auth = readYoutrackToken(); if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` }; const r = await request('/api/users/me?fields=id,name,login,email,guest,$type', auth.token); if (r.code !== 200 || !r.parsed) return { error: true, text: `Identitaet nicht lesbar: HTTP ${r.code} (${apiError(r, '')})` }; const u = r.parsed; const lines = [ '## YouTrack-Account', '', `- Login: **${u.login || '?'}**`, `- Name: ${u.name || '-'}`, `- E-Mail: ${u.email || '-'}`, `- Gast: ${u.guest ? 'ja' : 'nein'}`, `- ID: ${u.id || '-'}`, ]; return { error: false, text: lines.join('\n') }; } async function listProjects() { const auth = readYoutrackToken(); if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` }; const r = await request('/api/admin/projects?fields=shortName,name,description', auth.token); if (r.code === 403) return { error: true, text: 'Projektliste nicht sichtbar (403) fuer diesen Account.' }; if (r.code !== 200 || !Array.isArray(r.parsed)) { return { error: true, text: `Projektliste nicht lesbar: HTTP ${r.code} (${apiError(r, '')})` }; } const lines = ['## YouTrack-Projekte', '', '| Kurzname | Name |', '|---|---|']; for (const p of r.parsed) lines.push(`| ${p.shortName} | ${p.name || ''} |`); return { error: false, text: lines.join('\n') }; } async function searchIssues(args) { const auth = readYoutrackToken(); if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` }; const q = String((args && args.query) || '').trim(); const max = Math.min(50, Math.max(1, Number((args && args.max) || 10))); const query = q ? `query=${encodeURIComponent(q)}&` : 'query=&'; const r = await request( `/api/issues?${query}$top=${max}&fields=idReadable,summary,resolved,created,project(shortName,name)`, auth.token ); if (r.code !== 200 || !Array.isArray(r.parsed)) { return { error: true, text: `Suche fehlgeschlagen: HTTP ${r.code} (${apiError(r, '')})` }; } const lines = [ '## YouTrack-Issues', '', `Suche: \`${q || '(alle)'}\` — ${r.parsed.length} Treffer`, '', '| ID | Projekt | Zustand | Zusammenfassung |', '|---|---|---|---|', ]; for (const i of r.parsed) { const state = i.resolved ? 'erledigt' : 'offen'; const proj = (i.project && i.project.shortName) || '-'; lines.push(`| ${i.idReadable || i.id} | ${proj} | ${state} | ${String(i.summary || '').slice(0, 90)} |`); } return { error: false, text: lines.join('\n') }; } async function getIssue(args) { const auth = readYoutrackToken(); if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` }; const id = String((args && args.id) || '').trim(); if (!/^[A-Z0-9]+-\d+$/i.test(id)) return { error: true, text: `Ungueltige Kurz-ID "${id}".` }; const withComments = !!(args && args.include_comments); const fields = [ 'idReadable', 'summary', 'description', 'created', 'updated', 'resolved', 'reporter(login,name)', 'project(shortName,name)', 'customFields(id,name,$type,value(name,login))', ]; if (withComments) fields.push('comments(id,text,created,author(login,name))'); const r = await request(`/api/issues/${encodeURIComponent(id)}?fields=${encodeURIComponent(fields.join(','))}`, auth.token); if (r.code !== 200 || !r.parsed) { return { error: true, text: `Issue ${id} nicht lesbar: HTTP ${r.code} (${apiError(r, '')})` }; } const i = r.parsed; const lines = [ `## ${i.idReadable || id} — ${i.summary || '(ohne Zusammenfassung)'}`, '', `- Projekt: ${(i.project && (i.project.shortName + ' ' + (i.project.name || ''))) || '-'}`, `- Reporter: ${(i.reporter && (i.reporter.login || i.reporter.name)) || '-'}`, `- Erstellt: ${i.created ? new Date(i.created).toISOString().replace('T', ' ').slice(0, 16) + 'U' : '-'}`, i.updated ? `- Geaendert: ${new Date(i.updated).toISOString().replace('T', ' ').slice(0, 16) + 'U'}` : null, `- Status: **${i.resolved ? 'erledigt' : 'offen'}**`, '', '### Angepasste Felder', ].filter((l) => l !== null); const cfs = Array.isArray(i.customFields) ? i.customFields : []; if (cfs.length) { lines.push('', '| Feld | Wert |', '|---|---|'); for (const cf of cfs) lines.push(`| ${cf.name} | ${fmtValue(cf.value)} |`); } else { lines.push('', '(keine)'); } lines.push('', '### Beschreibung'); lines.push(String(i.description || '*(leer)*').slice(0, MAX_CHARS / 2)); if (withComments) { lines.push('', `### Kommentare (${Array.isArray(i.comments) ? i.comments.length : 0})`); const cs = Array.isArray(i.comments) ? i.comments : []; for (const c of cs.slice(0, 30)) { const who = (c.author && (c.author.login || c.author.name)) || '?'; const when = c.created ? new Date(c.created).toISOString().replace('T', ' ').slice(0, 16) + 'U' : '?'; lines.push(`- **${who}** (${when}): ${String(c.text || '').slice(0, 600)}`); } } return { error: false, text: lines.join('\n') }; } async function resolveTypesFor(project, token) { const r = await request( `/api/issues?query=${encodeURIComponent(`project: ${project}`)}&$top=1&fields=customFields(id,name,$type)`, token ); const map = {}; if (r.code === 200 && Array.isArray(r.parsed) && r.parsed.length) { for (const cf of r.parsed[0].customFields || []) if (cf.name && cf.$type) map[cf.name] = cf.$type; } return map; } function normaliseCustomFields(fields, types) { return (fields || []).map((f) => { const name = String(f.name || '').trim(); let value = f.value; if (value !== null && typeof value === 'object' && !value.name && !value.id) { throw new Error(`Feld "${name}": Wert muss ein String (Enum-Name) oder Objekt mit id/name sein.`); } if (typeof value === 'string') value = { name: value }; return { name, $type: (types && types[name]) || DEFAULT_TYPES[name] || 'SingleEnumIssueCustomField', value, }; }); } async function createIssue(args) { const auth = readYoutrackToken(); if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` }; const project = String((args && args.project) || '').trim(); const summary = String((args && args.summary) || '').trim(); if (!project) return { error: true, text: 'Projekt-Kurzname fehlt.' }; if (!summary) return { error: true, text: 'Zusammenfassung fehlt.' }; const types = await resolveTypesFor(project, auth.token); const body = { project: { shortName: project }, summary }; if (args && args.description) body.description = String(args.description); if (args && args.custom_fields && args.custom_fields.length) { try { body.customFields = normaliseCustomFields(args.custom_fields, types); } catch (e) { return { error: true, text: e.message }; } } const r = await request(`/api/issues?fields=idReadable,summary,created,customFields(id,name,$type,value(name))`, auth.token, { method: 'POST', body, }); if (r.code !== 200 || !r.parsed || !r.parsed.idReadable) { return { error: true, text: `Anlegen fehlgeschlagen: HTTP ${r.code} (${apiError(r, 'Pflichtfelder evtl. unvollstaendig')})` }; } const lines = [ `## Issue angelegt: ${r.parsed.idReadable}`, '', `- Zusammenfassung: ${r.parsed.summary}`, ]; for (const cf of r.parsed.customFields || []) lines.push(`- ${cf.name}: ${fmtValue(cf.value)}`); lines.push('', `Tipp: Details liest du mit get_issue (id=${r.parsed.idReadable}).`); return { error: false, text: lines.join('\n') }; } async function addComment(args) { const auth = readYoutrackToken(); if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` }; const id = String((args && args.id) || '').trim(); const text = String((args && args.text) || '').trim(); if (!/^[A-Z0-9]+-\d+$/i.test(id)) return { error: true, text: `Ungueltige Kurz-ID "${id}".` }; if (!text) return { error: true, text: 'Kommentartext fehlt.' }; const r = await request(`/api/issues/${encodeURIComponent(id)}/comments?fields=id,text,author(login)`, auth.token, { method: 'POST', body: { text }, }); if (r.code !== 200 || !r.parsed) { return { error: true, text: `Kommentar fehlgeschlagen: HTTP ${r.code} (${apiError(r, '')})` }; } return { error: false, text: `Kommentar zu ${id} hinzugefuegt (von ${r.parsed.author ? r.parsed.author.login : '?'}).`, }; } async function updateFields(args) { const auth = readYoutrackToken(); if (auth.error) return { error: true, text: `Token nicht verfuegbar: ${auth.error}` }; const id = String((args && args.id) || '').trim(); if (!/^[A-Z0-9]+-\d+$/i.test(id)) return { error: true, text: `Ungueltige Kurz-ID "${id}".` }; const f = (args && args.custom_fields) || []; if (!Array.isArray(f) || !f.length) return { error: true, text: 'Keine Felder angegeben.' }; const cur = await request( `/api/issues/${encodeURIComponent(id)}?fields=customFields(id,name,$type)`, auth.token ); const types = {}; if (cur.code === 200 && cur.parsed && Array.isArray(cur.parsed.customFields)) { for (const cf of cur.parsed.customFields) if (cf.name && cf.$type) types[cf.name] = cf.$type; } let customFields; try { customFields = normaliseCustomFields(f, types); } catch (e) { return { error: true, text: e.message }; } const r = await request( `/api/issues/${encodeURIComponent(id)}?fields=idReadable,customFields(name,value(name,login))`, auth.token, { method: 'POST', body: { customFields } } ); if (r.code !== 200 || !r.parsed) { return { error: true, text: `Aendern fehlgeschlagen: HTTP ${r.code} (${apiError(r, '')})` }; } const lines = ['## Felder aktualisiert', '', `- Issue: ${r.parsed.idReadable || id}`, '', '| Feld | Wert |', '|---|---|']; for (const cf of r.parsed.customFields || []) lines.push(`| ${cf.name} | ${fmtValue(cf.value)} |`); return { error: false, text: lines.join('\n') }; } function reply(id, result) { process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result }) + '\n'); } function replyError(id, code, message) { process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } }) + '\n'); } let buf = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', (chunk) => { buf += chunk; let idx; while ((idx = buf.indexOf('\n')) >= 0) { const line = buf.slice(0, idx).trim(); buf = buf.slice(idx + 1); if (!line) continue; handle(line); } }); function toolAnnotations(name) { const read = !['create_issue', 'add_comment', 'update_issue_fields'].includes(name); return { title: name.replace(/_/g, ' '), readOnlyHint: read, destructiveHint: false, idempotentHint: read, openWorldHint: true, }; } function handle(line) { let msg; try { msg = JSON.parse(line); } catch (e) { process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }) + '\n'); return; } const { id, method, params } = msg; if (method === 'notifications/initialized' || (id === undefined && method)) return; if (method === 'initialize') { reply(id, { protocolVersion: (params && params.protocolVersion) || '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'youtrack', version: '1.0.0' }, }); return; } if (method === 'ping') { reply(id, {}); return; } if (method === 'tools/list') { reply(id, { tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema, annotations: toolAnnotations(name), })), }); return; } if (method === 'tools/call') { const name = params && params.name; const args = (params && params.arguments) || {}; const dispatch = { me: [false, () => me()], list_projects: [false, () => listProjects()], search_issues: [false, () => searchIssues(args)], get_issue: [false, () => getIssue(args)], create_issue: [false, () => createIssue(args)], add_comment: [false, () => addComment(args)], update_issue_fields: [false, () => updateFields(args)], }; const entry = dispatch[name]; if (!entry) { reply(id, { content: [{ type: 'text', text: `Unbekanntes Werkzeug: ${name}` }], isError: true }); return; } entry[1]() .then((r) => reply(id, { content: [{ type: 'text', text: r.text }], isError: Boolean(r.error) })) .catch((e) => reply(id, { content: [{ type: 'text', text: `Interner Fehler: ${e.message || e}` }], isError: true })); return; } replyError(id, -32601, 'Method not found'); }