@mtaap/mcp 0.1.3 → 0.2.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/dist/cli.js CHANGED
@@ -1,39 +1,1620 @@
1
1
  #!/usr/bin/env node
2
- import {
3
- createMCPServer
4
- } from "./chunk-7YL3QGGO.js";
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/index.ts
27
+ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
28
+ var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
29
+
30
+ // src/version.ts
31
+ var VERSION = "0.2.1";
32
+
33
+ // ../../packages/core/dist/constants/enums.js
34
+ var TaskState;
35
+ (function(TaskState3) {
36
+ TaskState3["BACKLOG"] = "BACKLOG";
37
+ TaskState3["READY"] = "READY";
38
+ TaskState3["IN_PROGRESS"] = "IN_PROGRESS";
39
+ TaskState3["REVIEW"] = "REVIEW";
40
+ TaskState3["DONE"] = "DONE";
41
+ })(TaskState || (TaskState = {}));
42
+ var UserRole;
43
+ (function(UserRole2) {
44
+ UserRole2["ADMIN"] = "ADMIN";
45
+ UserRole2["MEMBER"] = "MEMBER";
46
+ })(UserRole || (UserRole = {}));
47
+ var ProjectType;
48
+ (function(ProjectType2) {
49
+ ProjectType2["TEAM"] = "TEAM";
50
+ ProjectType2["PERSONAL"] = "PERSONAL";
51
+ })(ProjectType || (ProjectType = {}));
52
+ var ProjectOrigin;
53
+ (function(ProjectOrigin2) {
54
+ ProjectOrigin2["CREATED"] = "CREATED";
55
+ ProjectOrigin2["PROMOTED"] = "PROMOTED";
56
+ })(ProjectOrigin || (ProjectOrigin = {}));
57
+ var TaskPriority;
58
+ (function(TaskPriority2) {
59
+ TaskPriority2["LOW"] = "LOW";
60
+ TaskPriority2["MEDIUM"] = "MEDIUM";
61
+ TaskPriority2["HIGH"] = "HIGH";
62
+ TaskPriority2["CRITICAL"] = "CRITICAL";
63
+ })(TaskPriority || (TaskPriority = {}));
64
+ var DeploymentMode;
65
+ (function(DeploymentMode2) {
66
+ DeploymentMode2["SAAS"] = "saas";
67
+ DeploymentMode2["ONPREM"] = "onprem";
68
+ })(DeploymentMode || (DeploymentMode = {}));
69
+ var ErrorType;
70
+ (function(ErrorType3) {
71
+ ErrorType3["BUILD_FAILURE"] = "BUILD_FAILURE";
72
+ ErrorType3["TEST_FAILURE"] = "TEST_FAILURE";
73
+ ErrorType3["CONFLICT"] = "CONFLICT";
74
+ ErrorType3["AUTH_ERROR"] = "AUTH_ERROR";
75
+ ErrorType3["OTHER"] = "OTHER";
76
+ })(ErrorType || (ErrorType = {}));
77
+ var PRStatus;
78
+ (function(PRStatus2) {
79
+ PRStatus2["OPEN"] = "OPEN";
80
+ PRStatus2["CLOSED"] = "CLOSED";
81
+ PRStatus2["MERGED"] = "MERGED";
82
+ PRStatus2["DELETED"] = "DELETED";
83
+ })(PRStatus || (PRStatus = {}));
84
+ var PricingTier;
85
+ (function(PricingTier2) {
86
+ PricingTier2["FREE"] = "FREE";
87
+ PricingTier2["PRO"] = "PRO";
88
+ PricingTier2["ENTERPRISE"] = "ENTERPRISE";
89
+ })(PricingTier || (PricingTier = {}));
90
+ var ApiKeyPermission;
91
+ (function(ApiKeyPermission2) {
92
+ ApiKeyPermission2["READ"] = "READ";
93
+ ApiKeyPermission2["WRITE"] = "WRITE";
94
+ ApiKeyPermission2["ADMIN"] = "ADMIN";
95
+ })(ApiKeyPermission || (ApiKeyPermission = {}));
96
+ var WebSocketEventType;
97
+ (function(WebSocketEventType2) {
98
+ WebSocketEventType2["TASK_ASSIGNED"] = "task.assigned";
99
+ WebSocketEventType2["TASK_ABANDONED"] = "task.abandoned";
100
+ WebSocketEventType2["TASK_PROGRESS"] = "task.progress";
101
+ WebSocketEventType2["TASK_PR_CREATED"] = "task.pr_created";
102
+ WebSocketEventType2["TASK_REVIEW_REQUESTED"] = "task.review_requested";
103
+ WebSocketEventType2["TASK_COMPLETED"] = "task.completed";
104
+ WebSocketEventType2["TASK_ERROR"] = "task.error";
105
+ WebSocketEventType2["TASK_STATE_CHANGED"] = "task.state_changed";
106
+ WebSocketEventType2["MEMBER_JOINED"] = "member.joined";
107
+ })(WebSocketEventType || (WebSocketEventType = {}));
108
+ var AuthProvider;
109
+ (function(AuthProvider2) {
110
+ AuthProvider2["CREDENTIALS"] = "credentials";
111
+ AuthProvider2["LDAP"] = "ldap";
112
+ AuthProvider2["SSO"] = "sso";
113
+ })(AuthProvider || (AuthProvider = {}));
114
+ var SubscriptionStatus;
115
+ (function(SubscriptionStatus2) {
116
+ SubscriptionStatus2["ACTIVE"] = "ACTIVE";
117
+ SubscriptionStatus2["INACTIVE"] = "INACTIVE";
118
+ SubscriptionStatus2["PAST_DUE"] = "PAST_DUE";
119
+ SubscriptionStatus2["CANCELED"] = "CANCELED";
120
+ SubscriptionStatus2["INCOMPLETE"] = "INCOMPLETE";
121
+ })(SubscriptionStatus || (SubscriptionStatus = {}));
122
+ var EventType;
123
+ (function(EventType2) {
124
+ EventType2["AUTH"] = "AUTH";
125
+ EventType2["AUTHORIZATION"] = "AUTHORIZATION";
126
+ EventType2["ACCESS"] = "ACCESS";
127
+ EventType2["MODIFICATION"] = "MODIFICATION";
128
+ })(EventType || (EventType = {}));
129
+
130
+ // ../../packages/core/dist/constants/state-machine.js
131
+ var VALID_TRANSITIONS = {
132
+ [TaskState.BACKLOG]: [TaskState.READY],
133
+ [TaskState.READY]: [TaskState.BACKLOG, TaskState.IN_PROGRESS],
134
+ [TaskState.IN_PROGRESS]: [
135
+ TaskState.BACKLOG,
136
+ TaskState.READY,
137
+ TaskState.REVIEW
138
+ ],
139
+ [TaskState.REVIEW]: [
140
+ TaskState.BACKLOG,
141
+ TaskState.READY,
142
+ TaskState.IN_PROGRESS,
143
+ TaskState.DONE
144
+ ],
145
+ [TaskState.DONE]: []
146
+ };
147
+
148
+ // ../../packages/core/dist/version.js
149
+ var VERSION2 = "0.1.0";
150
+
151
+ // ../../packages/core/dist/config/index.js
152
+ var DEPLOYMENT_MODE = process.env.DEPLOYMENT_MODE || "saas";
153
+ var config = {
154
+ version: VERSION2,
155
+ deploymentMode: DEPLOYMENT_MODE,
156
+ billing: {
157
+ enabled: DEPLOYMENT_MODE === "saas",
158
+ revenuecat: {
159
+ publicKey: process.env.REVENUECAT_PUBLIC_API_KEY,
160
+ stripeKey: process.env.STRIPE_SECRET_KEY
161
+ // Required by RevenueCat Web Billing
162
+ }
163
+ },
164
+ licensing: {
165
+ enabled: DEPLOYMENT_MODE === "onprem",
166
+ licenseKey: process.env.LICENSE_KEY
167
+ },
168
+ auth: {
169
+ credentials: true,
170
+ ldap: process.env.LDAP_ENABLED === "true"
171
+ },
172
+ git: {
173
+ deleteMergedBranches: process.env.DELETE_MERGED_BRANCHES !== "false",
174
+ enforceConventionalCommits: process.env.ENFORCE_CONVENTIONAL_COMMITS === "true",
175
+ defaultBaseBranch: process.env.DEFAULT_BASE_BRANCH || "develop"
176
+ },
177
+ pricing: {
178
+ maxPersonalProjects: {
179
+ FREE: 2,
180
+ PRO: 5,
181
+ ENTERPRISE: 10
182
+ },
183
+ maxCollaboratorsPerProject: {
184
+ FREE: 3,
185
+ PRO: -1,
186
+ ENTERPRISE: -1
187
+ },
188
+ maxProjectsPerOrg: {
189
+ FREE: 5,
190
+ PRO: -1,
191
+ ENTERPRISE: -1
192
+ },
193
+ maxSeats: {
194
+ FREE: 3,
195
+ PRO: -1,
196
+ ENTERPRISE: -1
197
+ },
198
+ // Default seats when subscription doesn't specify an explicit seat count
199
+ defaultSeats: {
200
+ FREE: 3,
201
+ PRO: 10,
202
+ ENTERPRISE: 999999
203
+ }
204
+ },
205
+ features: {
206
+ stripe: {
207
+ enabled: DEPLOYMENT_MODE === "saas"
208
+ },
209
+ gitlab: {
210
+ enabled: true
211
+ },
212
+ ldap: {
213
+ enabled: process.env.LDAP_ENABLED === "true"
214
+ },
215
+ auditLogs: {
216
+ enabled: process.env.AUDIT_LOGS_ENABLED === "true"
217
+ }
218
+ },
219
+ api: {
220
+ apiKey: {
221
+ defaultExpiryDays: 90,
222
+ prefix: "usr_"
223
+ },
224
+ rateLimit: {
225
+ requestsPerMinute: 100,
226
+ requestsPerHour: 1e3
227
+ }
228
+ },
229
+ limits: {
230
+ projectNameMaxLength: 100,
231
+ taskDescriptionMaxLength: 5e3,
232
+ notesMaxLength: 500,
233
+ conventionsNotesMaxLength: 500,
234
+ recentCompletedTasksLimit: 10
235
+ }
236
+ };
237
+ var DEFAULT_SEAT_LIMITS = {
238
+ [PricingTier.FREE]: config.pricing.defaultSeats.FREE,
239
+ [PricingTier.PRO]: config.pricing.defaultSeats.PRO,
240
+ [PricingTier.ENTERPRISE]: config.pricing.defaultSeats.ENTERPRISE
241
+ };
242
+
243
+ // ../../packages/core/dist/types/index.js
244
+ var import_zod = require("zod");
245
+ var UserIdSchema = import_zod.z.string().regex(/^usr_[a-zA-Z0-9]+$/);
246
+ var UserSchema = import_zod.z.object({
247
+ id: UserIdSchema,
248
+ email: import_zod.z.string().email(),
249
+ name: import_zod.z.string().min(1).max(255),
250
+ role: import_zod.z.nativeEnum(UserRole),
251
+ organizationId: import_zod.z.string().optional(),
252
+ lastActiveAt: import_zod.z.coerce.date().optional(),
253
+ createdAt: import_zod.z.coerce.date()
254
+ });
255
+ var OrganizationUserSchema = import_zod.z.object({
256
+ id: import_zod.z.number().int(),
257
+ userId: UserIdSchema,
258
+ organizationId: import_zod.z.string(),
259
+ roleId: import_zod.z.nativeEnum(UserRole).optional(),
260
+ user: UserSchema.pick({ id: true, email: true, name: true, role: true }),
261
+ createdAt: import_zod.z.coerce.date()
262
+ });
263
+ var OrganizationIdSchema = import_zod.z.string().regex(/^org_[a-zA-Z0-9]+$/);
264
+ var OrganizationSchema = import_zod.z.object({
265
+ id: OrganizationIdSchema,
266
+ name: import_zod.z.string().min(1).max(255),
267
+ slug: import_zod.z.string().min(1).max(100).regex(/^[a-z0-9-]+$/),
268
+ logoUrl: import_zod.z.string().url().nullable(),
269
+ accentColor: import_zod.z.string().regex(/^#[0-9A-Fa-f]{6}$/).nullable(),
270
+ tenantName: import_zod.z.string().nullable(),
271
+ pricingTier: import_zod.z.nativeEnum(PricingTier),
272
+ createdAt: import_zod.z.coerce.date()
273
+ });
274
+ var OrganizationSettingsSchema = import_zod.z.object({
275
+ organizationId: OrganizationIdSchema,
276
+ ldapEnabled: import_zod.z.boolean(),
277
+ ldapUrl: import_zod.z.string().url().nullable(),
278
+ ldapBindDN: import_zod.z.string().nullable(),
279
+ ldapSearchBase: import_zod.z.string().nullable(),
280
+ deleteMergedBranches: import_zod.z.boolean(),
281
+ enforceConventionalCommits: import_zod.z.boolean(),
282
+ maxPersonalProjectsPerUser: import_zod.z.number().int().min(0)
283
+ });
284
+ var TagSchema = import_zod.z.object({
285
+ id: import_zod.z.string(),
286
+ name: import_zod.z.string().min(1).max(50),
287
+ organizationId: OrganizationIdSchema,
288
+ createdAt: import_zod.z.coerce.date()
289
+ });
290
+ var ProjectIdSchema = import_zod.z.string().regex(/^prj_[a-zA-Z0-9]+$/);
291
+ var ProjectSchema = import_zod.z.object({
292
+ id: ProjectIdSchema,
293
+ name: import_zod.z.string().min(1).max(100),
294
+ description: import_zod.z.string().max(500).nullable(),
295
+ type: import_zod.z.nativeEnum(ProjectType),
296
+ origin: import_zod.z.nativeEnum(ProjectOrigin),
297
+ organizationId: OrganizationIdSchema,
298
+ ownerId: UserIdSchema.nullable(),
299
+ repositoryUrl: import_zod.z.string().url(),
300
+ baseBranch: import_zod.z.string().default("develop"),
301
+ tags: import_zod.z.array(import_zod.z.string()),
302
+ createdAt: import_zod.z.coerce.date(),
303
+ updatedAt: import_zod.z.coerce.date()
304
+ });
305
+ var EpicIdSchema = import_zod.z.string().regex(/^epc_[a-zA-Z0-9]+$/);
306
+ var EpicSchema = import_zod.z.object({
307
+ id: EpicIdSchema,
308
+ projectId: ProjectIdSchema,
309
+ name: import_zod.z.string().min(1).max(200),
310
+ description: import_zod.z.string().nullable(),
311
+ createdAt: import_zod.z.coerce.date(),
312
+ updatedAt: import_zod.z.coerce.date()
313
+ });
314
+ var TaskIdSchema = import_zod.z.string().regex(/^tsk_[a-zA-Z0-9]+$/);
315
+ var TaskSchema = import_zod.z.object({
316
+ id: TaskIdSchema,
317
+ projectId: ProjectIdSchema,
318
+ epicId: EpicIdSchema.nullable(),
319
+ title: import_zod.z.string().min(1).max(200),
320
+ description: import_zod.z.string().max(5e3),
321
+ state: import_zod.z.nativeEnum(TaskState),
322
+ priority: import_zod.z.nativeEnum(TaskPriority),
323
+ assigneeId: UserIdSchema.nullable(),
324
+ createdBy: UserIdSchema.nullable(),
325
+ assignedAt: import_zod.z.coerce.date().nullable(),
326
+ startedAt: import_zod.z.coerce.date().nullable(),
327
+ completedAt: import_zod.z.coerce.date().nullable(),
328
+ branchName: import_zod.z.string().nullable(),
329
+ pullRequestUrl: import_zod.z.string().url().nullable(),
330
+ pullRequestNumber: import_zod.z.number().int().nullable(),
331
+ pullRequestStatus: import_zod.z.nativeEnum(PRStatus).nullable(),
332
+ errorType: import_zod.z.nativeEnum(ErrorType).nullable(),
333
+ errorMessage: import_zod.z.string().max(1e3).nullable(),
334
+ createdAt: import_zod.z.coerce.date(),
335
+ updatedAt: import_zod.z.coerce.date()
336
+ });
337
+ var AcceptanceCriterionSchema = import_zod.z.object({
338
+ id: import_zod.z.string(),
339
+ taskId: TaskIdSchema,
340
+ description: import_zod.z.string().min(1).max(500),
341
+ completed: import_zod.z.boolean(),
342
+ completedAt: import_zod.z.coerce.date().nullable(),
343
+ order: import_zod.z.number().int(),
344
+ createdAt: import_zod.z.coerce.date()
345
+ });
346
+ var ProgressUpdateSchema = import_zod.z.object({
347
+ id: import_zod.z.string(),
348
+ taskId: TaskIdSchema,
349
+ userId: UserIdSchema,
350
+ message: import_zod.z.string().max(2e3),
351
+ checkpoints: import_zod.z.array(import_zod.z.string()).optional(),
352
+ createdAt: import_zod.z.coerce.date()
353
+ });
354
+ var TaskNoteSchema = import_zod.z.object({
355
+ id: import_zod.z.string(),
356
+ taskId: TaskIdSchema,
357
+ userId: UserIdSchema,
358
+ content: import_zod.z.string().max(500),
359
+ createdAt: import_zod.z.coerce.date()
360
+ });
361
+ var ApiKeyIdSchema = import_zod.z.string().regex(/^key_[a-zA-Z0-9]+$/);
362
+ var ApiKeySchema = import_zod.z.object({
363
+ id: ApiKeyIdSchema,
364
+ userId: UserIdSchema,
365
+ name: import_zod.z.string().min(1).max(100),
366
+ keyHash: import_zod.z.string(),
367
+ permissions: import_zod.z.nativeEnum(ApiKeyPermission),
368
+ lastUsedAt: import_zod.z.coerce.date().nullable(),
369
+ expiresAt: import_zod.z.coerce.date().nullable(),
370
+ revoked: import_zod.z.boolean(),
371
+ createdAt: import_zod.z.coerce.date()
372
+ });
373
+ var SubscriptionIdSchema = import_zod.z.string();
374
+ var SubscriptionSchema = import_zod.z.object({
375
+ id: SubscriptionIdSchema,
376
+ organizationId: OrganizationIdSchema,
377
+ pricingTier: import_zod.z.nativeEnum(PricingTier),
378
+ seats: import_zod.z.number().int().min(0),
379
+ stripeSubscriptionId: import_zod.z.string().nullable(),
380
+ stripeCustomerId: import_zod.z.string().nullable(),
381
+ status: import_zod.z.enum(["active", "past_due", "canceled", "incomplete"]),
382
+ currentPeriodStart: import_zod.z.coerce.date(),
383
+ currentPeriodEnd: import_zod.z.coerce.date(),
384
+ createdAt: import_zod.z.coerce.date()
385
+ });
386
+ var ProjectCollaboratorSchema = import_zod.z.object({
387
+ id: import_zod.z.string(),
388
+ projectId: ProjectIdSchema,
389
+ userId: UserIdSchema,
390
+ addedBy: UserIdSchema,
391
+ createdAt: import_zod.z.coerce.date()
392
+ });
393
+
394
+ // ../../packages/core/dist/validation/index.js
395
+ var import_zod2 = require("zod");
396
+ var ListProjectsInputSchema = import_zod2.z.object({
397
+ workspaceType: import_zod2.z.preprocess((val) => typeof val === "string" ? val.toUpperCase() : val, import_zod2.z.enum(["TEAM", "PERSONAL", "ALL"]).optional())
398
+ });
399
+ var ListTasksInputSchema = import_zod2.z.object({
400
+ projectId: import_zod2.z.string().optional(),
401
+ state: import_zod2.z.nativeEnum(TaskState).optional(),
402
+ assigneeId: import_zod2.z.string().optional()
403
+ });
404
+ var GetTaskInputSchema = import_zod2.z.object({
405
+ taskId: import_zod2.z.string().regex(/^tsk_[a-zA-Z0-9]+$/)
406
+ });
407
+ var AssignTaskInputSchema = import_zod2.z.object({
408
+ projectId: import_zod2.z.string().regex(/^prj_[a-zA-Z0-9]+$/),
409
+ taskId: import_zod2.z.string().regex(/^tsk_[a-zA-Z0-9]+$/),
410
+ expectedState: import_zod2.z.nativeEnum(TaskState).default(TaskState.READY)
411
+ });
412
+ var UpdateProgressInputSchema = import_zod2.z.object({
413
+ taskId: import_zod2.z.string().regex(/^tsk_[a-zA-Z0-9]+$/),
414
+ statusMessage: import_zod2.z.string().max(1e3).optional(),
415
+ completedCheckpointIds: import_zod2.z.array(import_zod2.z.string()).optional(),
416
+ currentCheckpointIndex: import_zod2.z.number().int().optional()
417
+ });
418
+ var CompleteTaskInputSchema = import_zod2.z.object({
419
+ projectId: import_zod2.z.string().regex(/^prj_[a-zA-Z0-9]+$/),
420
+ taskId: import_zod2.z.string().regex(/^tsk_[a-zA-Z0-9]+$/),
421
+ pullRequestTitle: import_zod2.z.string().min(1).max(300).optional(),
422
+ pullRequestBody: import_zod2.z.string().max(1e4).optional()
423
+ });
424
+ var ReportErrorInputSchema = import_zod2.z.object({
425
+ taskId: import_zod2.z.string().regex(/^tsk_[a-zA-Z0-9]+$/),
426
+ errorType: import_zod2.z.nativeEnum(ErrorType),
427
+ errorMessage: import_zod2.z.string().min(1).max(1e3),
428
+ context: import_zod2.z.string().max(2e3).optional()
429
+ });
430
+ var GetProjectContextInputSchema = import_zod2.z.object({
431
+ projectId: import_zod2.z.string().regex(/^prj_[a-zA-Z0-9]+$/)
432
+ });
433
+ var AddNoteInputSchema = import_zod2.z.object({
434
+ taskId: import_zod2.z.string().regex(/^tsk_[a-zA-Z0-9]+$/),
435
+ content: import_zod2.z.string().min(1).max(500)
436
+ });
437
+ var AbandonTaskInputSchema = import_zod2.z.object({
438
+ projectId: import_zod2.z.string().regex(/^prj_[a-zA-Z0-9]+$/),
439
+ taskId: import_zod2.z.string().regex(/^tsk_[a-zA-Z0-9]+$/),
440
+ deleteBranch: import_zod2.z.boolean().optional()
441
+ });
442
+ var CreatePersonalProjectInputSchema = import_zod2.z.object({
443
+ name: import_zod2.z.string().min(1).max(100),
444
+ description: import_zod2.z.string().max(500).optional(),
445
+ repositoryUrl: import_zod2.z.string().url()
446
+ });
447
+ var CheckActiveTaskInputSchema = import_zod2.z.object({});
448
+ var CreateOrganizationInputSchema = import_zod2.z.object({
449
+ name: import_zod2.z.string().min(1).max(255),
450
+ slug: import_zod2.z.string().min(1).max(100).regex(/^[a-z0-9-]+$/).optional()
451
+ });
452
+ var UpdateOrganizationInputSchema = import_zod2.z.object({
453
+ organizationId: import_zod2.z.string().regex(/^org_[a-zA-Z0-9]+$/),
454
+ name: import_zod2.z.string().min(1).max(255).optional(),
455
+ logoUrl: import_zod2.z.string().url().nullable().optional(),
456
+ accentColor: import_zod2.z.string().regex(/^#[0-9A-Fa-f]{6}$/, "Invalid hex color format. Expected #RRGGBB").nullable().optional(),
457
+ tenantName: import_zod2.z.string().max(255).nullable().optional()
458
+ });
459
+ var CreateProjectInputSchema = import_zod2.z.object({
460
+ name: import_zod2.z.string().min(1).max(100),
461
+ description: import_zod2.z.string().max(500).optional(),
462
+ type: import_zod2.z.nativeEnum(ProjectType),
463
+ repositoryUrl: import_zod2.z.string().url(),
464
+ baseBranch: import_zod2.z.string().default("develop").optional(),
465
+ tags: import_zod2.z.array(import_zod2.z.string()).default([])
466
+ });
467
+ var UpdateProjectInputSchema = import_zod2.z.object({
468
+ projectId: import_zod2.z.string().min(1).optional(),
469
+ name: import_zod2.z.string().min(1).max(100).optional(),
470
+ description: import_zod2.z.string().max(500).optional(),
471
+ repositoryUrl: import_zod2.z.string().url().optional(),
472
+ baseBranch: import_zod2.z.string().optional(),
473
+ tags: import_zod2.z.array(import_zod2.z.string()).optional()
474
+ });
475
+ var CreateEpicInputSchema = import_zod2.z.object({
476
+ projectId: import_zod2.z.string().regex(/^prj_[a-zA-Z0-9]+$/),
477
+ name: import_zod2.z.string().min(1).max(200),
478
+ description: import_zod2.z.string().max(2e3).optional()
479
+ });
480
+ var CreateTaskInputSchema = import_zod2.z.object({
481
+ projectId: import_zod2.z.string().min(1),
482
+ epicId: import_zod2.z.string().min(1).nullable().optional(),
483
+ title: import_zod2.z.string().min(1).max(200),
484
+ description: import_zod2.z.string().max(5e3),
485
+ priority: import_zod2.z.nativeEnum(TaskPriority).default(TaskPriority.MEDIUM),
486
+ acceptanceCriteria: import_zod2.z.array(import_zod2.z.object({
487
+ description: import_zod2.z.string().min(1).max(500)
488
+ })).min(1)
489
+ });
490
+ var UpdateTaskInputSchema = import_zod2.z.object({
491
+ taskId: import_zod2.z.string().min(1),
492
+ title: import_zod2.z.string().min(1).max(200).optional(),
493
+ description: import_zod2.z.string().max(5e3).optional(),
494
+ priority: import_zod2.z.nativeEnum(TaskPriority).optional(),
495
+ state: import_zod2.z.nativeEnum(TaskState).optional(),
496
+ assigneeId: import_zod2.z.string().nullable().optional(),
497
+ acceptanceCriteria: import_zod2.z.array(import_zod2.z.object({
498
+ id: import_zod2.z.string().optional(),
499
+ description: import_zod2.z.string().min(1).max(500),
500
+ completed: import_zod2.z.boolean().optional()
501
+ })).optional()
502
+ });
503
+ var AssignTaskWebappInputSchema = import_zod2.z.object({
504
+ taskId: import_zod2.z.string().min(1),
505
+ userId: import_zod2.z.string().min(1)
506
+ });
507
+ var CreateTagInputSchema = import_zod2.z.object({
508
+ organizationId: import_zod2.z.string().regex(/^org_[a-zA-Z0-9]+$/),
509
+ name: import_zod2.z.string().min(1).max(50).regex(/^[a-zA-Z0-9\s-]+$/)
510
+ });
511
+ var UpdateTagInputSchema = import_zod2.z.object({
512
+ name: import_zod2.z.string().min(1).max(50).regex(/^[a-zA-Z0-9\s-]+$/)
513
+ });
514
+ var UpdateOrganizationSettingsInputSchema = import_zod2.z.object({
515
+ organizationId: import_zod2.z.string().regex(/^org_[a-zA-Z0-9]+$/),
516
+ ldapEnabled: import_zod2.z.boolean().optional(),
517
+ ldapUrl: import_zod2.z.string().url().nullable().optional(),
518
+ ldapBindDN: import_zod2.z.string().nullable().optional(),
519
+ ldapSearchBase: import_zod2.z.string().nullable().optional(),
520
+ deleteMergedBranches: import_zod2.z.boolean().optional(),
521
+ enforceConventionalCommits: import_zod2.z.boolean().optional(),
522
+ maxPersonalProjectsPerUser: import_zod2.z.number().int().min(0).optional(),
523
+ logoUrl: import_zod2.z.string().url().nullable().optional(),
524
+ accentColor: import_zod2.z.string().regex(/^#[0-9A-Fa-f]{6}$/, "Invalid hex color format. Expected #RRGGBB").nullable().optional(),
525
+ tenantName: import_zod2.z.string().max(255).nullable().optional()
526
+ });
527
+ var InviteUserInputSchema = import_zod2.z.object({
528
+ organizationId: import_zod2.z.string().regex(/^org_[a-zA-Z0-9]+$/),
529
+ email: import_zod2.z.string().email(),
530
+ role: import_zod2.z.nativeEnum(UserRole).default(UserRole.MEMBER),
531
+ tags: import_zod2.z.array(import_zod2.z.string()).default([])
532
+ });
533
+ var AssignUserTagsInputSchema = import_zod2.z.object({
534
+ userId: import_zod2.z.string().regex(/^usr_[a-zA-Z0-9]+$/),
535
+ tags: import_zod2.z.array(import_zod2.z.string()).min(0)
536
+ });
537
+ var InviteCollaboratorInputSchema = import_zod2.z.object({
538
+ projectId: import_zod2.z.string().regex(/^prj_[a-zA-Z0-9]+$/),
539
+ email: import_zod2.z.string().email()
540
+ });
541
+ var PublishProjectInputSchema = import_zod2.z.object({
542
+ projectId: import_zod2.z.string().regex(/^prj_[a-zA-Z0-9]+$/),
543
+ transferOwnership: import_zod2.z.boolean().default(false),
544
+ tags: import_zod2.z.array(import_zod2.z.string()).min(1)
545
+ });
546
+ var GenerateApiKeyInputSchema = import_zod2.z.object({
547
+ name: import_zod2.z.string().min(1).max(100),
548
+ expiresInDays: import_zod2.z.number().int().min(1).max(365).default(90),
549
+ permissions: import_zod2.z.nativeEnum(ApiKeyPermission).default(ApiKeyPermission.WRITE)
550
+ });
551
+ var RevokeApiKeyInputSchema = import_zod2.z.object({
552
+ keyId: import_zod2.z.string().regex(/^key_[a-zA-Z0-9]+$/)
553
+ });
554
+ var LoginInputSchema = import_zod2.z.object({
555
+ email: import_zod2.z.string().email(),
556
+ password: import_zod2.z.string().min(8).max(255)
557
+ });
558
+ var RegisterInputSchema = import_zod2.z.object({
559
+ email: import_zod2.z.string().email(),
560
+ password: import_zod2.z.string().min(8).max(255),
561
+ name: import_zod2.z.string().min(1).max(255),
562
+ organizationSlug: import_zod2.z.string().min(1).max(100).regex(/^[a-z0-9-]+$/).optional()
563
+ });
564
+
565
+ // ../../packages/core/dist/logging/metrics.js
566
+ var metrics = /* @__PURE__ */ new Map();
567
+ function labelsToKey(labels) {
568
+ if (!labels || Object.keys(labels).length === 0)
569
+ return "";
570
+ return Object.entries(labels).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}="${v}"`).join(",");
571
+ }
572
+ function createCounter(name, help) {
573
+ const data = {
574
+ name,
575
+ type: "counter",
576
+ help,
577
+ values: /* @__PURE__ */ new Map()
578
+ };
579
+ metrics.set(name, data);
580
+ return {
581
+ inc(labels, value = 1) {
582
+ const key = labelsToKey(labels);
583
+ const current = data.values.get(key) || 0;
584
+ data.values.set(key, current + value);
585
+ }
586
+ };
587
+ }
588
+ function createGauge(name, help) {
589
+ const data = {
590
+ name,
591
+ type: "gauge",
592
+ help,
593
+ values: /* @__PURE__ */ new Map()
594
+ };
595
+ metrics.set(name, data);
596
+ return {
597
+ set(labels, value) {
598
+ const key = labelsToKey(labels);
599
+ data.values.set(key, value);
600
+ },
601
+ inc(labels, value = 1) {
602
+ const key = labelsToKey(labels);
603
+ const current = data.values.get(key) || 0;
604
+ data.values.set(key, current + value);
605
+ },
606
+ dec(labels, value = 1) {
607
+ const key = labelsToKey(labels);
608
+ const current = data.values.get(key) || 0;
609
+ data.values.set(key, current - value);
610
+ }
611
+ };
612
+ }
613
+ function createHistogram(name, help, buckets = [5e-3, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]) {
614
+ const data = {
615
+ name,
616
+ type: "histogram",
617
+ help,
618
+ values: /* @__PURE__ */ new Map(),
619
+ buckets
620
+ };
621
+ metrics.set(name, data);
622
+ return {
623
+ observe(labels, value) {
624
+ const baseKey = labelsToKey(labels);
625
+ const sumKey = `${baseKey}|sum`;
626
+ const countKey = `${baseKey}|count`;
627
+ data.values.set(sumKey, (data.values.get(sumKey) || 0) + value);
628
+ data.values.set(countKey, (data.values.get(countKey) || 0) + 1);
629
+ for (const bucket of buckets) {
630
+ const bucketKey = `${baseKey}|le="${bucket}"`;
631
+ if (value <= bucket) {
632
+ data.values.set(bucketKey, (data.values.get(bucketKey) || 0) + 1);
633
+ }
634
+ }
635
+ const infKey = `${baseKey}|le="+Inf"`;
636
+ data.values.set(infKey, (data.values.get(infKey) || 0) + 1);
637
+ }
638
+ };
639
+ }
640
+ var httpRequestsTotal = createCounter("mtaap_http_requests_total", "Total number of HTTP requests");
641
+ var httpRequestDuration = createHistogram("mtaap_http_request_duration_seconds", "HTTP request duration in seconds");
642
+ var activeUsers = createGauge("mtaap_active_users", "Number of active users");
643
+ var tasksTotal = createCounter("mtaap_tasks_total", "Total number of tasks by state");
644
+ var taskStateChanges = createCounter("mtaap_task_state_changes_total", "Total number of task state changes");
645
+ var httpErrorsTotal = createCounter("mtaap_http_errors_total", "Total number of HTTP errors");
646
+ var httpActiveConnections = createGauge("mtaap_http_active_connections", "Number of active HTTP connections");
647
+ var newSignupsTotal = createCounter("mtaap_new_signups_total", "Total number of new user signups");
648
+ var loginSuccessTotal = createCounter("mtaap_login_success_total", "Total number of successful logins");
649
+ var loginFailureTotal = createCounter("mtaap_login_failure_total", "Total number of failed logins");
650
+ var dbConnectionPoolActive = createGauge("mtaap_db_connection_pool_active", "Number of active database connections");
651
+ var dbConnectionPoolIdle = createGauge("mtaap_db_connection_pool_idle", "Number of idle database connections");
652
+ var dbConnectionPoolMax = createGauge("mtaap_db_connection_pool_max", "Maximum number of database connections");
653
+ var dbQueryDuration = createHistogram("mtaap_db_query_duration_seconds", "Database query duration in seconds");
654
+ var dbSlowQueriesTotal = createCounter("mtaap_db_slow_queries_total", "Total number of slow database queries (>1s)");
655
+ var dbErrorsTotal = createCounter("mtaap_db_errors_total", "Total number of database errors");
656
+ var tasksCreatedTotal = createCounter("mtaap_tasks_created_total", "Total number of tasks created");
657
+ var tasksAssignedTotal = createCounter("mtaap_tasks_assigned_total", "Total number of tasks assigned");
658
+ var tasksCompletedTotal = createCounter("mtaap_tasks_completed_total", "Total number of tasks completed");
659
+ var tasksByState = createGauge("mtaap_tasks_by_state", "Number of tasks by state");
660
+
661
+ // ../../packages/core/dist/logging/performance-monitor.js
662
+ var MAX_SAMPLES = 1e3;
663
+ var ALERT_COOLDOWN_MS = 5 * 60 * 1e3;
664
+ var DEFAULT_THRESHOLDS = {
665
+ api: {
666
+ p50: 100,
667
+ p95: 500,
668
+ p99: 1e3
669
+ },
670
+ db: {
671
+ p95: 100,
672
+ p99: 500
673
+ },
674
+ webvitals: {
675
+ FCP: 2e3,
676
+ LCP: 2500,
677
+ FID: 100,
678
+ CLS: 0.1
679
+ }
680
+ };
681
+ function cloneThresholds() {
682
+ return Object.fromEntries(Object.entries(DEFAULT_THRESHOLDS).map(([category, metrics2]) => [
683
+ category,
684
+ { ...metrics2 }
685
+ ]));
686
+ }
687
+ function labelsToKey2(labels) {
688
+ if (!labels || Object.keys(labels).length === 0)
689
+ return "";
690
+ return Object.entries(labels).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${key}="${value}"`).join(",");
691
+ }
692
+ function percentile(sortedValues, percentileValue) {
693
+ if (sortedValues.length === 0)
694
+ return 0;
695
+ const rank = Math.ceil(percentileValue / 100 * sortedValues.length);
696
+ const index = Math.min(Math.max(rank - 1, 0), sortedValues.length - 1);
697
+ return sortedValues[index];
698
+ }
699
+ var CircularBuffer = class {
700
+ capacity;
701
+ values = [];
702
+ index = 0;
703
+ size = 0;
704
+ constructor(capacity) {
705
+ this.capacity = capacity;
706
+ }
707
+ add(value) {
708
+ if (this.size < this.capacity) {
709
+ this.values.push(value);
710
+ this.size += 1;
711
+ this.index = this.size % this.capacity;
712
+ return;
713
+ }
714
+ this.values[this.index] = value;
715
+ this.index = (this.index + 1) % this.capacity;
716
+ }
717
+ getValues() {
718
+ if (this.size < this.capacity) {
719
+ return this.values.slice(0, this.size);
720
+ }
721
+ return this.values.slice();
722
+ }
723
+ };
724
+ var PerformanceMonitor = class {
725
+ samples = /* @__PURE__ */ new Map();
726
+ thresholds = cloneThresholds();
727
+ alertCallback;
728
+ lastAlertTimestamps = /* @__PURE__ */ new Map();
729
+ recordTiming(category, name, durationMs, labels) {
730
+ if (!Number.isFinite(durationMs))
731
+ return;
732
+ const categoryMap = this.getCategoryMap(category);
733
+ const nameMap = this.getNameMap(categoryMap, name);
734
+ const labelKey = labelsToKey2(labels);
735
+ const buffer = nameMap.get(labelKey) ?? new CircularBuffer(MAX_SAMPLES);
736
+ buffer.add(durationMs);
737
+ nameMap.set(labelKey, buffer);
738
+ }
739
+ getPercentiles(category, name) {
740
+ const samples = this.collectSamples(category, name);
741
+ if (samples.length === 0) {
742
+ return { p50: 0, p95: 0, p99: 0 };
743
+ }
744
+ const sorted = [...samples].sort((a, b) => a - b);
745
+ return {
746
+ p50: percentile(sorted, 50),
747
+ p95: percentile(sorted, 95),
748
+ p99: percentile(sorted, 99)
749
+ };
750
+ }
751
+ checkThresholds() {
752
+ const alerts = [];
753
+ const now = Date.now();
754
+ const callbackAlerts = [];
755
+ for (const [category, nameMap] of this.samples) {
756
+ const thresholds = this.thresholds[category];
757
+ if (!thresholds)
758
+ continue;
759
+ for (const name of nameMap.keys()) {
760
+ const percentiles = this.getPercentiles(category, name);
761
+ for (const [metric, threshold] of Object.entries(thresholds)) {
762
+ const value = this.resolveMetricValue(metric, name, percentiles);
763
+ if (value === void 0 || value <= threshold)
764
+ continue;
765
+ const alert = {
766
+ category,
767
+ name,
768
+ metric,
769
+ value,
770
+ threshold
771
+ };
772
+ alerts.push(alert);
773
+ const alertKey = `${category}|${name}|${metric}`;
774
+ const lastAlertTime = this.lastAlertTimestamps.get(alertKey);
775
+ if (!lastAlertTime || now - lastAlertTime >= ALERT_COOLDOWN_MS) {
776
+ this.lastAlertTimestamps.set(alertKey, now);
777
+ callbackAlerts.push(alert);
778
+ }
779
+ }
780
+ }
781
+ }
782
+ if (callbackAlerts.length > 0 && this.alertCallback) {
783
+ this.alertCallback(callbackAlerts);
784
+ }
785
+ return alerts;
786
+ }
787
+ setAlertCallback(callback) {
788
+ this.alertCallback = callback;
789
+ }
790
+ setThreshold(category, metric, value) {
791
+ if (!this.thresholds[category]) {
792
+ this.thresholds[category] = {};
793
+ }
794
+ this.thresholds[category][metric] = value;
795
+ }
796
+ collectSamples(category, name) {
797
+ const categoryMap = this.samples.get(category);
798
+ if (!categoryMap)
799
+ return [];
800
+ const entries = name ? [[name, categoryMap.get(name)]] : Array.from(categoryMap.entries());
801
+ const samples = [];
802
+ for (const [, labelMap] of entries) {
803
+ if (!labelMap)
804
+ continue;
805
+ for (const buffer of labelMap.values()) {
806
+ samples.push(...buffer.getValues());
807
+ }
808
+ }
809
+ return samples;
810
+ }
811
+ resolveMetricValue(metric, name, percentiles) {
812
+ if (metric === "p50")
813
+ return percentiles.p50;
814
+ if (metric === "p95")
815
+ return percentiles.p95;
816
+ if (metric === "p99")
817
+ return percentiles.p99;
818
+ if (metric === name)
819
+ return percentiles.p95;
820
+ return void 0;
821
+ }
822
+ getCategoryMap(category) {
823
+ const existing = this.samples.get(category);
824
+ if (existing)
825
+ return existing;
826
+ const created = /* @__PURE__ */ new Map();
827
+ this.samples.set(category, created);
828
+ return created;
829
+ }
830
+ getNameMap(categoryMap, name) {
831
+ const existing = categoryMap.get(name);
832
+ if (existing)
833
+ return existing;
834
+ const created = /* @__PURE__ */ new Map();
835
+ categoryMap.set(name, created);
836
+ return created;
837
+ }
838
+ };
839
+ var defaultMonitor = new PerformanceMonitor();
840
+
841
+ // ../../packages/core/dist/logging/error-tracker.js
842
+ var NoOpErrorTracker = class {
843
+ captureError(error, context) {
844
+ console.error("Error captured:", error.message, context);
845
+ }
846
+ captureException(error, context) {
847
+ console.error("Exception captured:", error, context);
848
+ }
849
+ captureMessage(message, level, context) {
850
+ console[level === "warning" ? "warn" : level](`Message captured [${level}]:`, message, context);
851
+ }
852
+ setUser(user) {
853
+ console.log("User set:", user);
854
+ }
855
+ clearUser() {
856
+ console.log("User cleared");
857
+ }
858
+ };
859
+ var errorTrackerInstance = new NoOpErrorTracker();
860
+
861
+ // src/api-client.ts
862
+ var DEFAULT_TIMEOUT = 3e4;
863
+ var ApiError = class extends Error {
864
+ constructor(message, code, status, details) {
865
+ super(message);
866
+ this.code = code;
867
+ this.status = status;
868
+ this.details = details;
869
+ this.name = "ApiError";
870
+ }
871
+ };
872
+ var MCPApiClient = class {
873
+ baseUrl;
874
+ apiKey;
875
+ timeout;
876
+ debug;
877
+ authContext = null;
878
+ constructor(config2) {
879
+ this.baseUrl = config2.baseUrl.replace(/\/$/, "");
880
+ this.apiKey = config2.apiKey;
881
+ this.timeout = config2.timeout ?? DEFAULT_TIMEOUT;
882
+ this.debug = config2.debug ?? false;
883
+ }
884
+ /**
885
+ * Make an HTTP request to the API
886
+ */
887
+ async request(method, path, body) {
888
+ const url = `${this.baseUrl}${path}`;
889
+ const controller = new AbortController();
890
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
891
+ if (this.debug) {
892
+ console.error(`[mcp-api] ${method} ${url}`);
893
+ }
894
+ try {
895
+ const response = await fetch(url, {
896
+ method,
897
+ headers: {
898
+ "Content-Type": "application/json",
899
+ "X-API-Key": this.apiKey
900
+ },
901
+ body: body ? JSON.stringify(body) : void 0,
902
+ signal: controller.signal
903
+ });
904
+ clearTimeout(timeoutId);
905
+ const data = await response.json();
906
+ if (!response.ok) {
907
+ throw new ApiError(
908
+ data.error || "API request failed",
909
+ data.code || "UNKNOWN_ERROR",
910
+ response.status,
911
+ data.details
912
+ );
913
+ }
914
+ return data;
915
+ } catch (error) {
916
+ clearTimeout(timeoutId);
917
+ if (error instanceof ApiError) {
918
+ throw error;
919
+ }
920
+ if (error instanceof Error && error.name === "AbortError") {
921
+ throw new ApiError(
922
+ "Request timed out",
923
+ "TIMEOUT",
924
+ 408
925
+ );
926
+ }
927
+ throw new ApiError(
928
+ error instanceof Error ? error.message : "Unknown error",
929
+ "NETWORK_ERROR",
930
+ 0
931
+ );
932
+ }
933
+ }
934
+ /**
935
+ * Authenticate and get user context
936
+ */
937
+ async authenticate() {
938
+ const context = await this.request("GET", "/api/mcp/auth");
939
+ this.authContext = context;
940
+ return context;
941
+ }
942
+ /**
943
+ * Get cached auth context or authenticate
944
+ */
945
+ async getAuthContext() {
946
+ if (this.authContext) {
947
+ return this.authContext;
948
+ }
949
+ return this.authenticate();
950
+ }
951
+ /**
952
+ * List accessible projects
953
+ */
954
+ async listProjects(workspaceType = "ALL") {
955
+ return this.request(
956
+ "GET",
957
+ `/api/mcp/projects?workspaceType=${encodeURIComponent(workspaceType)}`
958
+ );
959
+ }
960
+ /**
961
+ * Get single project details
962
+ */
963
+ async getProject(projectId) {
964
+ return this.request("GET", `/api/mcp/projects/${projectId}`);
965
+ }
966
+ /**
967
+ * Get project context (README, stack, conventions)
968
+ */
969
+ async getProjectContext(projectId) {
970
+ return this.request(
971
+ "GET",
972
+ `/api/mcp/projects/${projectId}/context`
973
+ );
974
+ }
975
+ /**
976
+ * Create a personal project
977
+ */
978
+ async createPersonalProject(name, description, repositoryUrl) {
979
+ return this.request(
980
+ "POST",
981
+ "/api/mcp/projects/personal",
982
+ { name, description, repositoryUrl }
983
+ );
984
+ }
985
+ /**
986
+ * List tasks with optional filters
987
+ */
988
+ async listTasks(filters = {}) {
989
+ const params = new URLSearchParams();
990
+ if (filters.projectId) params.set("projectId", filters.projectId);
991
+ if (filters.state) params.set("state", filters.state);
992
+ if (filters.assigneeId) params.set("assigneeId", filters.assigneeId);
993
+ const queryString = params.toString();
994
+ const path = queryString ? `/api/mcp/tasks?${queryString}` : "/api/mcp/tasks";
995
+ return this.request("GET", path);
996
+ }
997
+ /**
998
+ * Get full task details
999
+ */
1000
+ async getTask(taskId) {
1001
+ return this.request("GET", `/api/mcp/tasks/${taskId}`);
1002
+ }
1003
+ /**
1004
+ * Assign task to current user and create branch
1005
+ */
1006
+ async assignTask(taskId, projectId, expectedState = TaskState.READY) {
1007
+ return this.request("POST", `/api/mcp/tasks/${taskId}/assign`, {
1008
+ projectId,
1009
+ expectedState
1010
+ });
1011
+ }
1012
+ /**
1013
+ * Update task progress
1014
+ */
1015
+ async updateProgress(taskId, data) {
1016
+ return this.request("POST", `/api/mcp/tasks/${taskId}/progress`, data);
1017
+ }
1018
+ /**
1019
+ * Complete task and create PR
1020
+ */
1021
+ async completeTask(taskId, projectId, pullRequestTitle, pullRequestBody) {
1022
+ return this.request("POST", `/api/mcp/tasks/${taskId}/complete`, {
1023
+ projectId,
1024
+ pullRequestTitle,
1025
+ pullRequestBody
1026
+ });
1027
+ }
1028
+ /**
1029
+ * Abandon task and optionally delete branch
1030
+ */
1031
+ async abandonTask(taskId, projectId, deleteBranch = false) {
1032
+ return this.request("POST", `/api/mcp/tasks/${taskId}/abandon`, {
1033
+ projectId,
1034
+ deleteBranch
1035
+ });
1036
+ }
1037
+ /**
1038
+ * Report task error
1039
+ */
1040
+ async reportError(taskId, errorType, errorMessage, context) {
1041
+ return this.request("POST", `/api/mcp/tasks/${taskId}/error`, {
1042
+ errorType,
1043
+ errorMessage,
1044
+ context
1045
+ });
1046
+ }
1047
+ /**
1048
+ * Add note to task
1049
+ */
1050
+ async addNote(taskId, content) {
1051
+ return this.request("POST", `/api/mcp/tasks/${taskId}/notes`, { content });
1052
+ }
1053
+ /**
1054
+ * Get GitHub token
1055
+ */
1056
+ async getGitHubToken(organizationId) {
1057
+ const path = organizationId ? `/api/mcp/github-token?organizationId=${encodeURIComponent(organizationId)}` : "/api/mcp/github-token";
1058
+ return this.request("GET", path);
1059
+ }
1060
+ };
1061
+ function createApiClientFromEnv() {
1062
+ const baseUrl = process.env.MTAAP_BASE_URL;
1063
+ const apiKey = process.env.MTAAP_API_KEY;
1064
+ if (!baseUrl) {
1065
+ throw new Error("MTAAP_BASE_URL environment variable is required");
1066
+ }
1067
+ if (!apiKey) {
1068
+ throw new Error("MTAAP_API_KEY environment variable is required");
1069
+ }
1070
+ return new MCPApiClient({
1071
+ baseUrl,
1072
+ apiKey,
1073
+ debug: process.env.MTAAP_DEBUG === "true"
1074
+ });
1075
+ }
1076
+
1077
+ // src/permissions.ts
1078
+ var PERMISSION_RANK = {
1079
+ READ: 1,
1080
+ WRITE: 2,
1081
+ ADMIN: 3
1082
+ };
1083
+ function assertApiKeyPermission(apiKey, required, toolName) {
1084
+ const actualRank = PERMISSION_RANK[apiKey.permissions] ?? 0;
1085
+ const requiredRank = PERMISSION_RANK[required] ?? 0;
1086
+ if (actualRank >= requiredRank) {
1087
+ return;
1088
+ }
1089
+ console.warn("API key permission violation", {
1090
+ keyId: apiKey.id,
1091
+ requiredPermission: required,
1092
+ actualPermission: apiKey.permissions,
1093
+ tool: toolName
1094
+ });
1095
+ const error = new Error(
1096
+ `API key lacks required permissions (required: ${required})`
1097
+ );
1098
+ error.status = 403;
1099
+ throw error;
1100
+ }
1101
+
1102
+ // src/index.ts
1103
+ async function createMCPServer() {
1104
+ const server = new import_mcp.McpServer({
1105
+ name: "mtaap",
1106
+ version: VERSION
1107
+ });
1108
+ const apiClient = createApiClientFromEnv();
1109
+ let authContext;
1110
+ try {
1111
+ authContext = await apiClient.authenticate();
1112
+ } catch (error) {
1113
+ if (error instanceof ApiError) {
1114
+ throw new Error(`Authentication failed: ${error.message}`);
1115
+ }
1116
+ throw error;
1117
+ }
1118
+ const mockApiKey = {
1119
+ permissions: authContext.permissions.includes("ADMIN") ? ApiKeyPermission.ADMIN : authContext.permissions.includes("WRITE") ? ApiKeyPermission.WRITE : ApiKeyPermission.READ
1120
+ };
1121
+ server.registerTool(
1122
+ "list_projects",
1123
+ {
1124
+ description: "List accessible projects (personal + team via tags)"
1125
+ },
1126
+ async (args) => {
1127
+ assertApiKeyPermission(
1128
+ mockApiKey,
1129
+ ApiKeyPermission.READ,
1130
+ "list_projects"
1131
+ );
1132
+ const validated = ListProjectsInputSchema.parse(args);
1133
+ try {
1134
+ const projects = await apiClient.listProjects(validated.workspaceType);
1135
+ return {
1136
+ content: [
1137
+ {
1138
+ type: "text",
1139
+ text: JSON.stringify(projects, null, 2)
1140
+ }
1141
+ ]
1142
+ };
1143
+ } catch (error) {
1144
+ return handleApiError(error);
1145
+ }
1146
+ }
1147
+ );
1148
+ server.registerTool(
1149
+ "list_tasks",
1150
+ {
1151
+ description: "Returns available tasks (filterable by project, state)"
1152
+ },
1153
+ async (args) => {
1154
+ assertApiKeyPermission(mockApiKey, ApiKeyPermission.READ, "list_tasks");
1155
+ const validated = ListTasksInputSchema.parse(args);
1156
+ try {
1157
+ const tasks = await apiClient.listTasks({
1158
+ projectId: validated.projectId,
1159
+ state: validated.state,
1160
+ assigneeId: validated.assigneeId
1161
+ });
1162
+ return {
1163
+ content: [
1164
+ {
1165
+ type: "text",
1166
+ text: JSON.stringify(tasks, null, 2)
1167
+ }
1168
+ ]
1169
+ };
1170
+ } catch (error) {
1171
+ return handleApiError(error);
1172
+ }
1173
+ }
1174
+ );
1175
+ server.registerTool(
1176
+ "get_task",
1177
+ {
1178
+ description: "Full task details including acceptance criteria"
1179
+ },
1180
+ async (args) => {
1181
+ assertApiKeyPermission(mockApiKey, ApiKeyPermission.READ, "get_task");
1182
+ const validated = GetTaskInputSchema.parse(args);
1183
+ try {
1184
+ const task = await apiClient.getTask(validated.taskId);
1185
+ return {
1186
+ content: [
1187
+ {
1188
+ type: "text",
1189
+ text: JSON.stringify(task, null, 2)
1190
+ }
1191
+ ]
1192
+ };
1193
+ } catch (error) {
1194
+ return handleApiError(error);
1195
+ }
1196
+ }
1197
+ );
1198
+ server.registerTool(
1199
+ "assign_task",
1200
+ {
1201
+ description: "Atomic claim - creates branch. Fails if already taken."
1202
+ },
1203
+ async (args) => {
1204
+ assertApiKeyPermission(
1205
+ mockApiKey,
1206
+ ApiKeyPermission.WRITE,
1207
+ "assign_task"
1208
+ );
1209
+ const validated = AssignTaskInputSchema.parse(args);
1210
+ try {
1211
+ const result = await apiClient.assignTask(
1212
+ validated.taskId,
1213
+ validated.projectId,
1214
+ validated.expectedState
1215
+ );
1216
+ return {
1217
+ content: [
1218
+ {
1219
+ type: "text",
1220
+ text: JSON.stringify(result, null, 2)
1221
+ }
1222
+ ]
1223
+ };
1224
+ } catch (error) {
1225
+ return handleApiError(error);
1226
+ }
1227
+ }
1228
+ );
1229
+ server.registerTool(
1230
+ "update_progress",
1231
+ {
1232
+ description: "Reports status, updates checkboxes, writes checkpoint"
1233
+ },
1234
+ async (args) => {
1235
+ assertApiKeyPermission(
1236
+ mockApiKey,
1237
+ ApiKeyPermission.WRITE,
1238
+ "update_progress"
1239
+ );
1240
+ const validated = UpdateProgressInputSchema.parse(args);
1241
+ try {
1242
+ const result = await apiClient.updateProgress(validated.taskId, {
1243
+ statusMessage: validated.statusMessage,
1244
+ completedCheckpointIds: validated.completedCheckpointIds,
1245
+ currentCheckpointIndex: validated.currentCheckpointIndex
1246
+ });
1247
+ return {
1248
+ content: [
1249
+ {
1250
+ type: "text",
1251
+ text: JSON.stringify(result, null, 2)
1252
+ }
1253
+ ]
1254
+ };
1255
+ } catch (error) {
1256
+ return handleApiError(error);
1257
+ }
1258
+ }
1259
+ );
1260
+ server.registerTool(
1261
+ "complete_task",
1262
+ {
1263
+ description: "Marks complete, triggers PR, deletes local state file"
1264
+ },
1265
+ async (args) => {
1266
+ assertApiKeyPermission(
1267
+ mockApiKey,
1268
+ ApiKeyPermission.WRITE,
1269
+ "complete_task"
1270
+ );
1271
+ const validated = CompleteTaskInputSchema.parse(args);
1272
+ try {
1273
+ const result = await apiClient.completeTask(
1274
+ validated.taskId,
1275
+ validated.projectId,
1276
+ validated.pullRequestTitle,
1277
+ validated.pullRequestBody
1278
+ );
1279
+ return {
1280
+ content: [
1281
+ {
1282
+ type: "text",
1283
+ text: JSON.stringify(result, null, 2)
1284
+ }
1285
+ ]
1286
+ };
1287
+ } catch (error) {
1288
+ return handleApiError(error);
1289
+ }
1290
+ }
1291
+ );
1292
+ server.registerTool(
1293
+ "check_active_task",
1294
+ {
1295
+ description: "Check for resumable task in .mtaap/active-task.json"
1296
+ },
1297
+ async () => {
1298
+ assertApiKeyPermission(
1299
+ mockApiKey,
1300
+ ApiKeyPermission.READ,
1301
+ "check_active_task"
1302
+ );
1303
+ const result = await checkActiveTask();
1304
+ return {
1305
+ content: [
1306
+ {
1307
+ type: "text",
1308
+ text: JSON.stringify(result, null, 2)
1309
+ }
1310
+ ]
1311
+ };
1312
+ }
1313
+ );
1314
+ server.registerTool(
1315
+ "report_error",
1316
+ {
1317
+ description: "Report unrecoverable error, displays on task in webapp"
1318
+ },
1319
+ async (args) => {
1320
+ assertApiKeyPermission(
1321
+ mockApiKey,
1322
+ ApiKeyPermission.WRITE,
1323
+ "report_error"
1324
+ );
1325
+ const validated = ReportErrorInputSchema.parse(args);
1326
+ try {
1327
+ const result = await apiClient.reportError(
1328
+ validated.taskId,
1329
+ validated.errorType,
1330
+ validated.errorMessage,
1331
+ validated.context
1332
+ );
1333
+ return {
1334
+ content: [
1335
+ {
1336
+ type: "text",
1337
+ text: JSON.stringify(result, null, 2)
1338
+ }
1339
+ ]
1340
+ };
1341
+ } catch (error) {
1342
+ return handleApiError(error);
1343
+ }
1344
+ }
1345
+ );
1346
+ server.registerTool(
1347
+ "get_project_context",
1348
+ {
1349
+ description: "Returns assembled context (README, stack, conventions)"
1350
+ },
1351
+ async (args) => {
1352
+ assertApiKeyPermission(
1353
+ mockApiKey,
1354
+ ApiKeyPermission.READ,
1355
+ "get_project_context"
1356
+ );
1357
+ const validated = GetProjectContextInputSchema.parse(args);
1358
+ try {
1359
+ const context = await apiClient.getProjectContext(validated.projectId);
1360
+ return {
1361
+ content: [
1362
+ {
1363
+ type: "text",
1364
+ text: JSON.stringify(context, null, 2)
1365
+ }
1366
+ ]
1367
+ };
1368
+ } catch (error) {
1369
+ return handleApiError(error);
1370
+ }
1371
+ }
1372
+ );
1373
+ server.registerTool(
1374
+ "add_note",
1375
+ {
1376
+ description: "Append implementation notes to task"
1377
+ },
1378
+ async (args) => {
1379
+ assertApiKeyPermission(mockApiKey, ApiKeyPermission.WRITE, "add_note");
1380
+ const validated = AddNoteInputSchema.parse(args);
1381
+ try {
1382
+ const result = await apiClient.addNote(
1383
+ validated.taskId,
1384
+ validated.content
1385
+ );
1386
+ return {
1387
+ content: [
1388
+ {
1389
+ type: "text",
1390
+ text: JSON.stringify(result, null, 2)
1391
+ }
1392
+ ]
1393
+ };
1394
+ } catch (error) {
1395
+ return handleApiError(error);
1396
+ }
1397
+ }
1398
+ );
1399
+ server.registerTool(
1400
+ "abandon_task",
1401
+ {
1402
+ description: "Unassign from a task and optionally delete the branch"
1403
+ },
1404
+ async (args) => {
1405
+ assertApiKeyPermission(
1406
+ mockApiKey,
1407
+ ApiKeyPermission.WRITE,
1408
+ "abandon_task"
1409
+ );
1410
+ const validated = AbandonTaskInputSchema.parse(args);
1411
+ try {
1412
+ const result = await apiClient.abandonTask(
1413
+ validated.taskId,
1414
+ validated.projectId,
1415
+ validated.deleteBranch
1416
+ );
1417
+ return {
1418
+ content: [
1419
+ {
1420
+ type: "text",
1421
+ text: JSON.stringify(result, null, 2)
1422
+ }
1423
+ ]
1424
+ };
1425
+ } catch (error) {
1426
+ return handleApiError(error);
1427
+ }
1428
+ }
1429
+ );
1430
+ server.registerTool(
1431
+ "create_personal_project",
1432
+ {
1433
+ description: "Create project in user's personal workspace"
1434
+ },
1435
+ async (args) => {
1436
+ assertApiKeyPermission(
1437
+ mockApiKey,
1438
+ ApiKeyPermission.WRITE,
1439
+ "create_personal_project"
1440
+ );
1441
+ const validated = CreatePersonalProjectInputSchema.parse(args);
1442
+ try {
1443
+ const result = await apiClient.createPersonalProject(
1444
+ validated.name,
1445
+ validated.description,
1446
+ validated.repositoryUrl
1447
+ );
1448
+ return {
1449
+ content: [
1450
+ {
1451
+ type: "text",
1452
+ text: JSON.stringify(result, null, 2)
1453
+ }
1454
+ ]
1455
+ };
1456
+ } catch (error) {
1457
+ return handleApiError(error);
1458
+ }
1459
+ }
1460
+ );
1461
+ server.registerTool(
1462
+ "get_version",
1463
+ {
1464
+ description: "Get the current MTAAP version"
1465
+ },
1466
+ async () => {
1467
+ assertApiKeyPermission(mockApiKey, ApiKeyPermission.READ, "get_version");
1468
+ return {
1469
+ content: [
1470
+ {
1471
+ type: "text",
1472
+ text: JSON.stringify(
1473
+ {
1474
+ version: VERSION,
1475
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1476
+ },
1477
+ null,
1478
+ 2
1479
+ )
1480
+ }
1481
+ ]
1482
+ };
1483
+ }
1484
+ );
1485
+ const transport = new import_stdio.StdioServerTransport();
1486
+ await server.connect(transport);
1487
+ }
1488
+ function handleApiError(error) {
1489
+ if (error instanceof ApiError) {
1490
+ return {
1491
+ content: [
1492
+ {
1493
+ type: "text",
1494
+ text: JSON.stringify(
1495
+ {
1496
+ error: error.message,
1497
+ code: error.code,
1498
+ status: error.status,
1499
+ details: error.details
1500
+ },
1501
+ null,
1502
+ 2
1503
+ )
1504
+ }
1505
+ ],
1506
+ isError: true
1507
+ };
1508
+ }
1509
+ const message = error instanceof Error ? error.message : String(error);
1510
+ return {
1511
+ content: [
1512
+ {
1513
+ type: "text",
1514
+ text: JSON.stringify({ error: message }, null, 2)
1515
+ }
1516
+ ],
1517
+ isError: true
1518
+ };
1519
+ }
1520
+ async function checkActiveTask() {
1521
+ const fs = await import("fs");
1522
+ const path = await import("path");
1523
+ const activeTaskPath = path.join(process.cwd(), ".mtaap", "active-task.json");
1524
+ try {
1525
+ await fs.promises.access(activeTaskPath);
1526
+ const content = await fs.promises.readFile(activeTaskPath, "utf-8");
1527
+ const activeTask = JSON.parse(content);
1528
+ return {
1529
+ hasActiveTask: true,
1530
+ task: activeTask
1531
+ };
1532
+ } catch {
1533
+ return {
1534
+ hasActiveTask: false,
1535
+ task: null
1536
+ };
1537
+ }
1538
+ }
5
1539
 
6
1540
  // src/cli.ts
7
1541
  function validateEnvironment() {
8
1542
  const errors = [];
9
- const warnings = [];
10
1543
  if (!process.env.MTAAP_API_KEY) {
11
1544
  errors.push(
12
- "MTAAP_API_KEY is required. Generate one at https://app.mtaap.io/settings/api-keys"
1545
+ "MTAAP_API_KEY is required. Generate one at https://collab.mtaap.de/settings/api-keys"
13
1546
  );
14
1547
  }
15
- if (!process.env.GITHUB_TOKEN) {
16
- warnings.push(
17
- "GITHUB_TOKEN is not set. Branch creation and PR features will not work."
1548
+ if (!process.env.MTAAP_BASE_URL) {
1549
+ errors.push(
1550
+ "MTAAP_BASE_URL is required. Set to https://collab.mtaap.de for cloud or your self-hosted URL."
18
1551
  );
19
1552
  }
20
- for (const warning of warnings) {
21
- console.error(`[mtaap-mcp] Warning: ${warning}`);
22
- }
23
1553
  if (errors.length > 0) {
24
1554
  for (const error of errors) {
25
1555
  console.error(`[mtaap-mcp] Error: ${error}`);
26
1556
  }
27
1557
  console.error("\nRequired environment variables:");
28
- console.error(" MTAAP_API_KEY Your MTAAP API key");
29
- console.error("\nOptional environment variables:");
30
- console.error(" GITHUB_TOKEN GitHub personal access token for git operations");
1558
+ console.error(" MTAAP_API_KEY Your MTAAP API key");
1559
+ console.error(" MTAAP_BASE_URL MTAAP webapp URL (e.g., https://collab.mtaap.de)");
1560
+ console.error("\nExample mcp.json configuration:");
1561
+ console.error(`{
1562
+ "mcpServers": {
1563
+ "mtaap": {
1564
+ "command": "npx",
1565
+ "args": ["@mtaap/mcp"],
1566
+ "env": {
1567
+ "MTAAP_API_KEY": "usr_your_api_key_here",
1568
+ "MTAAP_BASE_URL": "https://collab.mtaap.de"
1569
+ }
1570
+ }
1571
+ }
1572
+ }`);
1573
+ process.exit(1);
1574
+ }
1575
+ try {
1576
+ new URL(process.env.MTAAP_BASE_URL);
1577
+ } catch {
1578
+ console.error(`[mtaap-mcp] Error: MTAAP_BASE_URL is not a valid URL: ${process.env.MTAAP_BASE_URL}`);
1579
+ process.exit(1);
1580
+ }
1581
+ }
1582
+ async function checkConnectivity() {
1583
+ const baseUrl = process.env.MTAAP_BASE_URL;
1584
+ console.error(`[mtaap-mcp] Checking connectivity to ${baseUrl}...`);
1585
+ try {
1586
+ const response = await fetch(`${baseUrl}/api/mcp/auth`, {
1587
+ method: "GET",
1588
+ headers: {
1589
+ "X-API-Key": process.env.MTAAP_API_KEY
1590
+ },
1591
+ signal: AbortSignal.timeout(1e4)
1592
+ // 10 second timeout
1593
+ });
1594
+ if (!response.ok) {
1595
+ const data = await response.json().catch(() => ({}));
1596
+ if (response.status === 401) {
1597
+ console.error("[mtaap-mcp] Error: Invalid or expired API key");
1598
+ process.exit(1);
1599
+ }
1600
+ console.error(`[mtaap-mcp] Error: API returned ${response.status}: ${data.error || "Unknown error"}`);
1601
+ process.exit(1);
1602
+ }
1603
+ console.error("[mtaap-mcp] Connected successfully");
1604
+ } catch (error) {
1605
+ if (error instanceof Error && error.name === "TimeoutError") {
1606
+ console.error(`[mtaap-mcp] Error: Connection timed out to ${baseUrl}`);
1607
+ } else {
1608
+ console.error(`[mtaap-mcp] Error: Could not connect to ${baseUrl}`);
1609
+ console.error(`[mtaap-mcp] Details: ${error instanceof Error ? error.message : String(error)}`);
1610
+ }
31
1611
  process.exit(1);
32
1612
  }
33
1613
  }
34
1614
  async function main() {
35
1615
  console.error("[mtaap-mcp] Starting MTAAP MCP server...");
36
1616
  validateEnvironment();
1617
+ await checkConnectivity();
37
1618
  try {
38
1619
  await createMCPServer();
39
1620
  console.error("[mtaap-mcp] Server started successfully");