@goliapkg/sentori-cli 0.5.2 → 0.6.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/src/mcp.ts ADDED
@@ -0,0 +1,399 @@
1
+ // v1.2 W9 — Sentori MCP server.
2
+ //
3
+ // Stdio JSON-RPC 2.0 transport per the Model Context Protocol spec
4
+ // (https://modelcontextprotocol.io/). LLM clients (Claude Code,
5
+ // custom agents) spawn `sentori-cli mcp serve` as a subprocess and
6
+ // pipe MCP messages over stdin/stdout. Each tool call translates
7
+ // 1:1 to the existing admin API; the MCP layer is pure protocol
8
+ // glue + auth-passthrough.
9
+ //
10
+ // Why CLI-hosted instead of server-hosted MCP:
11
+ // - The Sentori server exposes admin endpoints over HTTPS already;
12
+ // spinning up a parallel MCP endpoint would duplicate auth +
13
+ // route boilerplate.
14
+ // - LLM clients expect MCP servers to be local stdio subprocesses
15
+ // (Claude Code config, gptme, etc.). The CLI is the natural
16
+ // binary to embed it in — the operator already has it installed
17
+ // and a token configured.
18
+ // - Easier to ship + version with the rest of the CLI.
19
+
20
+ import { createInterface } from 'node:readline'
21
+
22
+ import type { AdminUpload } from './native-artifacts.js'
23
+
24
+ type JsonRpcRequest = {
25
+ id?: number | string | null
26
+ jsonrpc: '2.0'
27
+ method: string
28
+ params?: Record<string, unknown>
29
+ }
30
+
31
+ type JsonRpcResponse = {
32
+ id?: number | string | null
33
+ jsonrpc: '2.0'
34
+ result?: unknown
35
+ error?: { code: number; message: string; data?: unknown }
36
+ }
37
+
38
+ type ToolHandler = (args: Record<string, unknown>, ctx: McpCtx) => Promise<unknown>
39
+
40
+ type ToolDef = {
41
+ name: string
42
+ description: string
43
+ inputSchema: Record<string, unknown>
44
+ handler: ToolHandler
45
+ }
46
+
47
+ type McpCtx = AdminUpload
48
+
49
+ /** Run the MCP server over stdio. Returns when stdin closes. */
50
+ export async function runMcpServer(ctx: McpCtx): Promise<void> {
51
+ const tools = buildTools()
52
+ const toolMap = new Map(tools.map((t) => [t.name, t]))
53
+
54
+ const rl = createInterface({ input: process.stdin })
55
+ for await (const line of rl) {
56
+ const trimmed = line.trim()
57
+ if (!trimmed) continue
58
+ let req: JsonRpcRequest
59
+ try {
60
+ req = JSON.parse(trimmed)
61
+ } catch {
62
+ // Per spec, malformed requests get a parse-error response with
63
+ // null id.
64
+ send({
65
+ error: { code: -32700, message: 'Parse error' },
66
+ id: null,
67
+ jsonrpc: '2.0',
68
+ })
69
+ continue
70
+ }
71
+ // Notifications (no `id`) get no response.
72
+ const isNotification = req.id === undefined || req.id === null
73
+ try {
74
+ const result = await dispatch(req, toolMap, ctx, tools)
75
+ if (!isNotification) {
76
+ send({ id: req.id ?? null, jsonrpc: '2.0', result })
77
+ }
78
+ } catch (e) {
79
+ if (!isNotification) {
80
+ send({
81
+ error: { code: -32603, message: (e as Error).message },
82
+ id: req.id ?? null,
83
+ jsonrpc: '2.0',
84
+ })
85
+ }
86
+ }
87
+ }
88
+ }
89
+
90
+ function send(resp: JsonRpcResponse): void {
91
+ process.stdout.write(JSON.stringify(resp) + '\n')
92
+ }
93
+
94
+ async function dispatch(
95
+ req: JsonRpcRequest,
96
+ toolMap: Map<string, ToolDef>,
97
+ ctx: McpCtx,
98
+ tools: ToolDef[],
99
+ ): Promise<unknown> {
100
+ switch (req.method) {
101
+ case 'initialize':
102
+ return {
103
+ capabilities: { tools: {} },
104
+ protocolVersion: '2024-11-05',
105
+ serverInfo: { name: 'sentori', version: '1.0' },
106
+ }
107
+ case 'notifications/initialized':
108
+ return {}
109
+ case 'tools/list':
110
+ return {
111
+ tools: tools.map((t) => ({
112
+ description: t.description,
113
+ inputSchema: t.inputSchema,
114
+ name: t.name,
115
+ })),
116
+ }
117
+ case 'tools/call': {
118
+ const params = (req.params ?? {}) as { arguments?: Record<string, unknown>; name?: string }
119
+ const name = params.name
120
+ if (typeof name !== 'string') throw new Error('missing tools/call.name')
121
+ const tool = toolMap.get(name)
122
+ if (!tool) throw new Error(`unknown tool: ${name}`)
123
+ const result = await tool.handler(params.arguments ?? {}, ctx)
124
+ return {
125
+ content: [
126
+ {
127
+ text: typeof result === 'string' ? result : JSON.stringify(result, null, 2),
128
+ type: 'text',
129
+ },
130
+ ],
131
+ }
132
+ }
133
+ default:
134
+ throw new Error(`method not found: ${req.method}`)
135
+ }
136
+ }
137
+
138
+ // ── Tool implementations ─────────────────────────────────────────
139
+
140
+ async function adminGet<T>(ctx: McpCtx, path: string): Promise<T> {
141
+ const url = `${ctx.apiUrl.replace(/\/+$/, '')}/admin/api${path}`
142
+ const resp = await fetch(url, {
143
+ headers: { Authorization: `Bearer ${ctx.token}` },
144
+ })
145
+ if (!resp.ok) throw new Error(`GET ${path} → ${resp.status} ${resp.statusText}`)
146
+ return (await resp.json()) as T
147
+ }
148
+
149
+ async function adminPatch<T>(ctx: McpCtx, path: string, body: unknown): Promise<T> {
150
+ const url = `${ctx.apiUrl.replace(/\/+$/, '')}/admin/api${path}`
151
+ const resp = await fetch(url, {
152
+ body: JSON.stringify(body),
153
+ headers: {
154
+ Authorization: `Bearer ${ctx.token}`,
155
+ 'Content-Type': 'application/json',
156
+ },
157
+ method: 'PATCH',
158
+ })
159
+ if (!resp.ok) throw new Error(`PATCH ${path} → ${resp.status} ${resp.statusText}`)
160
+ return (await resp.json()) as T
161
+ }
162
+
163
+ async function adminPost<T>(ctx: McpCtx, path: string, body: unknown): Promise<T> {
164
+ const url = `${ctx.apiUrl.replace(/\/+$/, '')}/admin/api${path}`
165
+ const resp = await fetch(url, {
166
+ body: body !== undefined ? JSON.stringify(body) : undefined,
167
+ headers: {
168
+ Authorization: `Bearer ${ctx.token}`,
169
+ 'Content-Type': 'application/json',
170
+ },
171
+ method: 'POST',
172
+ })
173
+ if (!resp.ok) throw new Error(`POST ${path} → ${resp.status} ${resp.statusText}`)
174
+ if (resp.status === 204) return null as T
175
+ return (await resp.json()) as T
176
+ }
177
+
178
+ async function adminPut<T>(ctx: McpCtx, path: string): Promise<T> {
179
+ const url = `${ctx.apiUrl.replace(/\/+$/, '')}/admin/api${path}`
180
+ const resp = await fetch(url, {
181
+ headers: { Authorization: `Bearer ${ctx.token}` },
182
+ method: 'PUT',
183
+ })
184
+ if (!resp.ok) throw new Error(`PUT ${path} → ${resp.status} ${resp.statusText}`)
185
+ if (resp.status === 204) return null as T
186
+ return (await resp.json()) as T
187
+ }
188
+
189
+ async function adminDelete<T>(ctx: McpCtx, path: string): Promise<T> {
190
+ const url = `${ctx.apiUrl.replace(/\/+$/, '')}/admin/api${path}`
191
+ const resp = await fetch(url, {
192
+ headers: { Authorization: `Bearer ${ctx.token}` },
193
+ method: 'DELETE',
194
+ })
195
+ if (!resp.ok) throw new Error(`DELETE ${path} → ${resp.status} ${resp.statusText}`)
196
+ if (resp.status === 204) return null as T
197
+ return (await resp.json()) as T
198
+ }
199
+
200
+ function asString(v: unknown, name: string): string {
201
+ if (typeof v !== 'string' || v.length === 0) {
202
+ throw new Error(`${name} is required (string)`)
203
+ }
204
+ return v
205
+ }
206
+
207
+ function asOptionalString(v: unknown): string | undefined {
208
+ if (v === undefined || v === null) return undefined
209
+ if (typeof v !== 'string') throw new Error('expected string')
210
+ return v
211
+ }
212
+
213
+ export function buildTools(): ToolDef[] {
214
+ return [
215
+ {
216
+ description:
217
+ 'List issues for a Sentori project, with optional status / priority / label filters.',
218
+ handler: async (args, ctx) => {
219
+ const projectId = asString(args.projectId, 'projectId')
220
+ const usp = new URLSearchParams()
221
+ const status = asOptionalString(args.status) ?? 'any'
222
+ usp.set('status', status)
223
+ if (args.priority) usp.set('priority', String(args.priority))
224
+ if (args.label) usp.set('labels', String(args.label))
225
+ if (typeof args.limit === 'number') usp.set('limit', String(args.limit))
226
+ return await adminGet(ctx, `/projects/${projectId}/issues?${usp}`)
227
+ },
228
+ inputSchema: {
229
+ properties: {
230
+ label: { type: 'string' },
231
+ limit: { type: 'number' },
232
+ priority: { type: 'string' },
233
+ projectId: { type: 'string' },
234
+ status: { type: 'string' },
235
+ },
236
+ required: ['projectId'],
237
+ type: 'object',
238
+ },
239
+ name: 'sentori_issue_list',
240
+ },
241
+ {
242
+ description: 'Get full detail for one Sentori issue including its activity feed.',
243
+ handler: async (args, ctx) => {
244
+ const projectId = asString(args.projectId, 'projectId')
245
+ const issueId = asString(args.issueId, 'issueId')
246
+ const [issue, activity] = await Promise.all([
247
+ adminGet(ctx, `/projects/${projectId}/issues/${issueId}`),
248
+ adminGet(ctx, `/projects/${projectId}/issues/${issueId}/activity`),
249
+ ])
250
+ return { activity, issue }
251
+ },
252
+ inputSchema: {
253
+ properties: {
254
+ issueId: { type: 'string' },
255
+ projectId: { type: 'string' },
256
+ },
257
+ required: ['projectId', 'issueId'],
258
+ type: 'object',
259
+ },
260
+ name: 'sentori_issue_get',
261
+ },
262
+ {
263
+ description: 'Add a comment to a Sentori issue.',
264
+ handler: async (args, ctx) => {
265
+ const projectId = asString(args.projectId, 'projectId')
266
+ const issueId = asString(args.issueId, 'issueId')
267
+ const body = asString(args.body, 'body')
268
+ return await adminPost(ctx, `/projects/${projectId}/issues/${issueId}/comments`, {
269
+ body,
270
+ })
271
+ },
272
+ inputSchema: {
273
+ properties: {
274
+ body: { type: 'string' },
275
+ issueId: { type: 'string' },
276
+ projectId: { type: 'string' },
277
+ },
278
+ required: ['projectId', 'issueId', 'body'],
279
+ type: 'object',
280
+ },
281
+ name: 'sentori_issue_comment',
282
+ },
283
+ {
284
+ description:
285
+ 'Transition an issue to a new status (active|silenced|muted|resolved|closed).',
286
+ handler: async (args, ctx) => {
287
+ const projectId = asString(args.projectId, 'projectId')
288
+ const issueId = asString(args.issueId, 'issueId')
289
+ const status = asString(args.status, 'status')
290
+ return await adminPatch(ctx, `/projects/${projectId}/issues/${issueId}`, {
291
+ status,
292
+ })
293
+ },
294
+ inputSchema: {
295
+ properties: {
296
+ issueId: { type: 'string' },
297
+ projectId: { type: 'string' },
298
+ status: {
299
+ enum: ['active', 'silenced', 'muted', 'resolved', 'closed'],
300
+ type: 'string',
301
+ },
302
+ },
303
+ required: ['projectId', 'issueId', 'status'],
304
+ type: 'object',
305
+ },
306
+ name: 'sentori_issue_transition',
307
+ },
308
+ {
309
+ description: 'Assign an issue to a user, or pass userId=null to unassign.',
310
+ handler: async (args, ctx) => {
311
+ const projectId = asString(args.projectId, 'projectId')
312
+ const issueId = asString(args.issueId, 'issueId')
313
+ const userId = args.userId === null ? null : asOptionalString(args.userId)
314
+ return await adminPatch(ctx, `/projects/${projectId}/issues/${issueId}`, {
315
+ assigneeUserId: userId ?? null,
316
+ })
317
+ },
318
+ inputSchema: {
319
+ properties: {
320
+ issueId: { type: 'string' },
321
+ projectId: { type: 'string' },
322
+ userId: { type: ['string', 'null'] },
323
+ },
324
+ required: ['projectId', 'issueId', 'userId'],
325
+ type: 'object',
326
+ },
327
+ name: 'sentori_issue_assign',
328
+ },
329
+ {
330
+ description: 'Set the triage priority on an issue.',
331
+ handler: async (args, ctx) => {
332
+ const projectId = asString(args.projectId, 'projectId')
333
+ const issueId = asString(args.issueId, 'issueId')
334
+ const priority = asString(args.priority, 'priority')
335
+ return await adminPatch(ctx, `/projects/${projectId}/issues/${issueId}`, {
336
+ priority,
337
+ })
338
+ },
339
+ inputSchema: {
340
+ properties: {
341
+ issueId: { type: 'string' },
342
+ priority: { enum: ['p0', 'p1', 'p2', 'p3'], type: 'string' },
343
+ projectId: { type: 'string' },
344
+ },
345
+ required: ['projectId', 'issueId', 'priority'],
346
+ type: 'object',
347
+ },
348
+ name: 'sentori_issue_set_priority',
349
+ },
350
+ {
351
+ description: 'Replace the label set on an issue. Pass [] to clear all.',
352
+ handler: async (args, ctx) => {
353
+ const projectId = asString(args.projectId, 'projectId')
354
+ const issueId = asString(args.issueId, 'issueId')
355
+ if (!Array.isArray(args.labels)) throw new Error('labels must be string[]')
356
+ const labels = args.labels.map((l) => {
357
+ if (typeof l !== 'string') throw new Error('each label must be a string')
358
+ return l
359
+ })
360
+ return await adminPatch(ctx, `/projects/${projectId}/issues/${issueId}`, {
361
+ labels,
362
+ })
363
+ },
364
+ inputSchema: {
365
+ properties: {
366
+ issueId: { type: 'string' },
367
+ labels: { items: { type: 'string' }, type: 'array' },
368
+ projectId: { type: 'string' },
369
+ },
370
+ required: ['projectId', 'issueId', 'labels'],
371
+ type: 'object',
372
+ },
373
+ name: 'sentori_issue_set_labels',
374
+ },
375
+ {
376
+ description:
377
+ 'Subscribe (watch=true) or unsubscribe (watch=false) the configured caller to an issue.',
378
+ handler: async (args, ctx) => {
379
+ const projectId = asString(args.projectId, 'projectId')
380
+ const issueId = asString(args.issueId, 'issueId')
381
+ const watch = args.watch === true
382
+ if (watch) {
383
+ return await adminPut(ctx, `/projects/${projectId}/issues/${issueId}/watch`)
384
+ }
385
+ return await adminDelete(ctx, `/projects/${projectId}/issues/${issueId}/watch`)
386
+ },
387
+ inputSchema: {
388
+ properties: {
389
+ issueId: { type: 'string' },
390
+ projectId: { type: 'string' },
391
+ watch: { type: 'boolean' },
392
+ },
393
+ required: ['projectId', 'issueId', 'watch'],
394
+ type: 'object',
395
+ },
396
+ name: 'sentori_issue_watch',
397
+ },
398
+ ]
399
+ }
package/src/push.ts ADDED
@@ -0,0 +1,174 @@
1
+ // v2.12 — `sentori-cli push *` commands.
2
+ //
3
+ // Wraps the v2.7 admin REST + v2.7 ingest endpoints so operators can
4
+ // drive credential CRUD, ad-hoc sends, and receipt lookups from the
5
+ // terminal without touching curl.
6
+ //
7
+ // `push send` POST /v1/push/send (ingest Bearer)
8
+ // `push receipt` GET /v1/push/receipts/:id (ingest Bearer)
9
+ // `push creds list` GET /admin/api/projects/:id/push/credentials (admin Bearer)
10
+ // `push creds set` PUT /admin/api/projects/:id/push/credentials (admin Bearer)
11
+ // `push creds delete` DELETE /admin/api/projects/:id/push/credentials/:provider
12
+
13
+ import { readFileSync } from 'node:fs'
14
+
15
+ export type PushClientConfig = {
16
+ apiUrl: string
17
+ projectId: string
18
+ token: string
19
+ }
20
+
21
+ type AdminCredentialRow = {
22
+ provider: string
23
+ config: Record<string, unknown>
24
+ updatedAt: string
25
+ }
26
+
27
+ type Ticket = {
28
+ id: string
29
+ status: 'queued' | 'sent' | 'failed'
30
+ providerOutcome?: string | null
31
+ error?: string | null
32
+ retryCount: number
33
+ createdAt: string
34
+ sentAt?: string | null
35
+ }
36
+
37
+ const VALID_PROVIDERS = new Set(['apns', 'fcm', 'webpush', 'hcm', 'mipush'])
38
+
39
+ function joinUrl(base: string, path: string): string {
40
+ return `${base.replace(/\/+$/, '')}${path}`
41
+ }
42
+
43
+ async function bearerFetch<T>(
44
+ url: string,
45
+ token: string,
46
+ init?: RequestInit,
47
+ ): Promise<T> {
48
+ const resp = await fetch(url, {
49
+ ...init,
50
+ headers: {
51
+ Authorization: `Bearer ${token}`,
52
+ 'Content-Type': 'application/json',
53
+ ...(init?.headers ?? {}),
54
+ },
55
+ })
56
+ if (!resp.ok) {
57
+ const detail = await resp.text().catch(() => '')
58
+ throw new Error(
59
+ `${resp.status} ${resp.statusText}${detail ? ` — ${detail.slice(0, 300)}` : ''}`,
60
+ )
61
+ }
62
+ const txt = await resp.text()
63
+ return (txt ? JSON.parse(txt) : null) as T
64
+ }
65
+
66
+ /** Parse a CLI flag value that may be `@file.json` (read from disk
67
+ * and parse) or a literal JSON string. */
68
+ export function parseJsonArg(raw: string, kind: string): unknown {
69
+ if (raw.startsWith('@')) {
70
+ const path = raw.slice(1)
71
+ const body = readFileSync(path, 'utf-8')
72
+ try {
73
+ return JSON.parse(body)
74
+ } catch (e) {
75
+ throw new Error(`${kind} file ${path} is not valid JSON: ${(e as Error).message}`)
76
+ }
77
+ }
78
+ try {
79
+ return JSON.parse(raw)
80
+ } catch (e) {
81
+ throw new Error(`${kind} arg is not valid JSON: ${(e as Error).message}`)
82
+ }
83
+ }
84
+
85
+ // ── credential CRUD ───────────────────────────────────────────────
86
+
87
+ export async function pushCredsList(cfg: PushClientConfig): Promise<AdminCredentialRow[]> {
88
+ return bearerFetch<AdminCredentialRow[]>(
89
+ joinUrl(cfg.apiUrl, `/admin/api/projects/${cfg.projectId}/push/credentials`),
90
+ cfg.token,
91
+ )
92
+ }
93
+
94
+ export async function pushCredsSet(
95
+ cfg: PushClientConfig,
96
+ provider: string,
97
+ config: unknown,
98
+ secret: unknown,
99
+ ): Promise<{ ok: boolean }> {
100
+ if (!VALID_PROVIDERS.has(provider)) {
101
+ throw new Error(
102
+ `invalid provider '${provider}'; expected one of ${[...VALID_PROVIDERS].join('/')}`,
103
+ )
104
+ }
105
+ return bearerFetch<{ ok: boolean }>(
106
+ joinUrl(cfg.apiUrl, `/admin/api/projects/${cfg.projectId}/push/credentials`),
107
+ cfg.token,
108
+ {
109
+ body: JSON.stringify({ provider, config, secret }),
110
+ method: 'PUT',
111
+ },
112
+ )
113
+ }
114
+
115
+ export async function pushCredsDelete(
116
+ cfg: PushClientConfig,
117
+ provider: string,
118
+ ): Promise<void> {
119
+ await bearerFetch<null>(
120
+ joinUrl(
121
+ cfg.apiUrl,
122
+ `/admin/api/projects/${cfg.projectId}/push/credentials/${provider}`,
123
+ ),
124
+ cfg.token,
125
+ { method: 'DELETE' },
126
+ )
127
+ }
128
+
129
+ // ── send / receipt ────────────────────────────────────────────────
130
+
131
+ export type SendOpts = {
132
+ to: string
133
+ title?: string
134
+ body?: string
135
+ data?: unknown
136
+ priority?: 'high' | 'normal'
137
+ ttl?: number
138
+ idempotencyKey?: string
139
+ }
140
+
141
+ export async function pushSend(cfg: PushClientConfig, opts: SendOpts): Promise<Ticket> {
142
+ const payload: Record<string, unknown> = {
143
+ to: opts.to,
144
+ title: opts.title,
145
+ body: opts.body,
146
+ data: opts.data,
147
+ idempotencyKey: opts.idempotencyKey,
148
+ }
149
+ if (opts.priority || opts.ttl != null) {
150
+ payload.options = { priority: opts.priority, ttl: opts.ttl }
151
+ }
152
+ const resp = await bearerFetch<{ tickets: Ticket[] }>(
153
+ joinUrl(cfg.apiUrl, '/v1/push/send'),
154
+ cfg.token,
155
+ {
156
+ body: JSON.stringify(payload),
157
+ method: 'POST',
158
+ },
159
+ )
160
+ if (!resp.tickets?.length) {
161
+ throw new Error('server returned no tickets')
162
+ }
163
+ return resp.tickets[0]!
164
+ }
165
+
166
+ export async function pushReceipt(
167
+ cfg: PushClientConfig,
168
+ sendId: string,
169
+ ): Promise<{ ticket: Ticket }> {
170
+ return bearerFetch<{ ticket: Ticket }>(
171
+ joinUrl(cfg.apiUrl, `/v1/push/receipts/${encodeURIComponent(sendId)}`),
172
+ cfg.token,
173
+ )
174
+ }