@dynamoi/mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,879 @@
1
+ // src/auth/protected-resource.ts
2
+ function buildProtectedResourceMetadata(options) {
3
+ return {
4
+ authorization_servers: options.authorizationServers,
5
+ resource: options.resource,
6
+ // Supabase OAuth Server (beta) can fail token exchange when `openid` is requested
7
+ // (it attempts to mint an ID token). Our MCP only needs an access token.
8
+ scopes_supported: options.scopesSupported ?? ["email", "profile"]
9
+ };
10
+ }
11
+ function buildWwwAuthenticateHeader(options) {
12
+ const scope = options.scope ?? "email profile";
13
+ return `Bearer resource_metadata="${options.resourceMetadataUrl}", scope="${scope}"`;
14
+ }
15
+
16
+ // src/auth/verify-token.ts
17
+ import { createRemoteJWKSet, jwtVerify } from "jose";
18
+ var jwksByUrl = /* @__PURE__ */ new Map();
19
+ function getRemoteJwks(jwksUrl) {
20
+ const existing = jwksByUrl.get(jwksUrl);
21
+ if (existing) {
22
+ return existing;
23
+ }
24
+ const created = createRemoteJWKSet(new URL(jwksUrl));
25
+ jwksByUrl.set(jwksUrl, created);
26
+ return created;
27
+ }
28
+ function extractClientId(payload) {
29
+ const direct = payload["client_id"];
30
+ if (typeof direct === "string" && direct.trim().length > 0) {
31
+ return direct;
32
+ }
33
+ const azp = payload["azp"];
34
+ if (typeof azp === "string" && azp.trim().length > 0) {
35
+ return azp;
36
+ }
37
+ return null;
38
+ }
39
+ async function verifyAccessToken(options) {
40
+ const jwks = getRemoteJwks(options.jwksUrl);
41
+ const verifyOptions = {
42
+ algorithms: ["ES256", "RS256"],
43
+ audience: options.audienceAllowlist,
44
+ issuer: options.issuer
45
+ };
46
+ const { payload } = await jwtVerify(options.token, jwks, verifyOptions);
47
+ const sub = typeof payload.sub === "string" ? payload.sub : null;
48
+ if (!sub) {
49
+ throw new Error("JWT missing sub");
50
+ }
51
+ const iss = typeof payload.iss === "string" ? payload.iss : null;
52
+ if (!iss) {
53
+ throw new Error("JWT missing iss");
54
+ }
55
+ const exp = typeof payload.exp === "number" ? payload.exp : null;
56
+ if (!exp) {
57
+ throw new Error("JWT missing exp");
58
+ }
59
+ const aud = payload.aud;
60
+ return {
61
+ aud,
62
+ clientId: extractClientId(payload),
63
+ exp,
64
+ iss,
65
+ sub
66
+ };
67
+ }
68
+
69
+ // src/server/create-server.ts
70
+ import {
71
+ McpServer,
72
+ ResourceTemplate
73
+ } from "@modelcontextprotocol/sdk/server/mcp.js";
74
+ import * as z3 from "zod/v4";
75
+
76
+ // src/version.ts
77
+ var DYNAMOI_MCP_VERSION = "__DYNAMOI_MCP_VERSION__";
78
+
79
+ // src/server/instructions.ts
80
+ var DYNAMOI_MCP_INSTRUCTIONS = `
81
+ You are operating Dynamoi's tools on behalf of the authenticated user. Dynamoi helps
82
+ music artists get more Spotify streams and YouTube creators grow their channels and
83
+ AdSense revenue \u2014 through automated ad campaigns on Meta (Facebook/Instagram) and
84
+ Google (YouTube).
85
+
86
+ Who uses Dynamoi:
87
+ - Independent artists promoting singles, albums, and playlists on Spotify
88
+ - Record labels managing campaigns across entire artist rosters with team roles and
89
+ consolidated billing
90
+ - YouTube creators of all kinds \u2014 music, education, gaming, vlogs, podcasts, tutorials
91
+ \u2014 growing channels and ad revenue
92
+
93
+ Pricing: $300/month converts 100% to ad credit. First month includes a 100% match \u2014
94
+ pay $300, get $600 in ad credit. Credits roll over for 12 months. No contracts, cancel
95
+ anytime. No agency fees, no retainers. Unlimited team seats and unlimited artists
96
+ included.
97
+
98
+ Every client gets white-glove onboarding and ongoing support \u2014 from connecting
99
+ platforms to optimizing channels for campaign performance, step by step.
100
+
101
+ Campaigns run from Dynamoi-managed ad accounts. Users complete a one-time platform
102
+ connection, then the AI-powered engine handles deployment and daily optimization.
103
+
104
+ Campaign types:
105
+
106
+ Smart Campaign (Meta Ads \u2192 Spotify):
107
+ Targeted Facebook and Instagram ads that drive real Spotify streams \u2014 no bots, no
108
+ pay-for-play. Includes free unlimited smart link landing pages for every release
109
+ (Spotify, Apple Music, YouTube Music, and more). Ad copy is AI-generated and localized
110
+ to each target market. Supports tracks, albums, and playlists.
111
+
112
+ YouTube Campaign (Google Ads \u2192 YouTube Growth):
113
+ The only ad platform that optimizes for total channel revenue, not just views. Google
114
+ Ads tracks views but can't see which views make money. Dynamoi merges Google Ads cost
115
+ data with YouTube AdSense revenue data to calculate the true revenue per view in each
116
+ country, then adjusts bids daily \u2014 exploring new markets with small bids, scaling
117
+ countries where viewer revenue is strong, and auto-pausing countries where the data
118
+ shows they can't cover their costs. The more data the system gathers, the more
119
+ precisely it optimizes. Campaigns require a YouTube playlist so one paid ad view can
120
+ lead to 2, 3, 4+ organic views as the viewer waterfalls down the playlist \u2014 optimizing
121
+ for depth of views means one ad click drives sustained organic growth. Ad copy is fully
122
+ internationalized in each target market's local language for better performance and
123
+ lower costs. Works for any type of YouTube channel.
124
+
125
+ Unlike smart-link-only services (Feature.fm, Linkfire, Hypeddit, ToneDen), Dynamoi is
126
+ an end-to-end promotion system: smart links + ad campaigns + AI optimization +
127
+ analytics + team management. All with transparent data and no contracts.
128
+
129
+ Principles:
130
+ - Be accurate. If uncertain, ask a clarifying question before acting.
131
+ - Never claim you changed something unless the tool returned status "success" or
132
+ "partial_success".
133
+ - Prefer read tools first before write tools. For writes, confirm intent and restate
134
+ what will change.
135
+ - All money values returned are display values. Do not attempt to infer internal costs.
136
+ - Budget minimums: $10/day (daily), $100 total (Smart Campaign), $50 total (YouTube).
137
+
138
+ Common workflows:
139
+ - Discovery: dynamoi_list_artists \u2192 dynamoi_list_campaigns \u2192 dynamoi_get_campaign \u2192
140
+ dynamoi_get_campaign_analytics
141
+ - Diagnose stuck campaign: dynamoi_get_campaign \u2192 dynamoi_get_platform_status \u2192
142
+ propose next steps
143
+ - Pause/resume: dynamoi_get_campaign (confirm) \u2192 dynamoi_pause_campaign or resume
144
+ - Budget update: dynamoi_get_campaign (confirm) \u2192 dynamoi_update_budget
145
+ - Launch: dynamoi_list_media_assets \u2192 dynamoi_launch_campaign
146
+ `.trim();
147
+
148
+ // src/server/prompts.ts
149
+ import * as z from "zod/v4";
150
+ function asTextPrompt(text) {
151
+ return {
152
+ messages: [
153
+ {
154
+ content: { text, type: "text" },
155
+ role: "user"
156
+ }
157
+ ]
158
+ };
159
+ }
160
+ function registerDynamoiPrompts(server) {
161
+ server.registerPrompt(
162
+ "dynamoi_audit_campaigns",
163
+ {
164
+ argsSchema: {
165
+ artistId: z.string().uuid().optional()
166
+ },
167
+ description: "Audit an artist's campaigns and summarize what is working and what to fix next.",
168
+ title: "Audit Campaigns"
169
+ },
170
+ (args) => asTextPrompt(
171
+ [
172
+ "Audit my campaigns in Dynamoi.",
173
+ args.artistId ? `Artist ID: ${args.artistId}` : "If no artistId is provided, start by listing artists and ask me which one to audit.",
174
+ "",
175
+ "Steps:",
176
+ "1. Use dynamoi_list_campaigns (and dynamoi_get_campaign_analytics for the last 7-14 days) to assess performance.",
177
+ "2. Identify any campaigns that are paused, failed, or stuck in a pre-active state and explain why using dynamoi_get_campaign and dynamoi_get_platform_status.",
178
+ "3. Recommend 3-5 next actions with clear priorities."
179
+ ].join("\n")
180
+ )
181
+ );
182
+ server.registerPrompt(
183
+ "dynamoi_release_launch_plan",
184
+ {
185
+ argsSchema: {
186
+ artistId: z.string().uuid().optional(),
187
+ contentTitle: z.string().trim().optional(),
188
+ contentType: z.enum(["TRACK", "ALBUM", "PLAYLIST", "VIDEO"]).optional()
189
+ },
190
+ description: "Create a pragmatic release launch plan and propose a Dynamoi campaign setup.",
191
+ title: "Release Launch Plan"
192
+ },
193
+ (args) => asTextPrompt(
194
+ [
195
+ "Help me plan a release launch using Dynamoi.",
196
+ args.artistId ? `Artist ID: ${args.artistId}` : "If no artistId is provided, list artists first.",
197
+ args.contentType ? `Content type: ${args.contentType}` : "",
198
+ args.contentTitle ? `Title: ${args.contentTitle}` : "",
199
+ "",
200
+ "Ask any missing questions first (links, creative, budget, countries, dates).",
201
+ "Then propose the simplest campaign plan that fits today\u2019s supported platforms:",
202
+ "- Smart Campaign (Meta) for Spotify/Apple Music releases",
203
+ "- YouTube campaign for videos",
204
+ "",
205
+ "If we proceed to launch:",
206
+ "- For Smart Campaign: use dynamoi_list_media_assets and then dynamoi_launch_campaign.",
207
+ "- For YouTube: use dynamoi_launch_campaign with youtubeVideoId."
208
+ ].filter(Boolean).join("\n")
209
+ )
210
+ );
211
+ server.registerPrompt(
212
+ "dynamoi_why_campaign_blocked",
213
+ {
214
+ argsSchema: {
215
+ campaignId: z.string().uuid()
216
+ },
217
+ description: "Diagnose why a campaign is blocked/stuck and recommend the next fix.",
218
+ title: "Why Is My Campaign Blocked?"
219
+ },
220
+ (args) => asTextPrompt(
221
+ [
222
+ "My campaign seems blocked or stuck. Diagnose it and tell me what to do next.",
223
+ `Campaign ID: ${args.campaignId}`,
224
+ "",
225
+ "Steps:",
226
+ "1. Use dynamoi_get_campaign to inspect current status and blockers.",
227
+ "2. Use dynamoi_get_platform_status for the artist to check Meta/Google connection state.",
228
+ "3. If appropriate, suggest safe next actions (pause/resume or budget update) and confirm before executing."
229
+ ].join("\n")
230
+ )
231
+ );
232
+ }
233
+
234
+ // src/server/tools.ts
235
+ import * as z2 from "zod/v4";
236
+ var ToolFormatSchema = z2.enum(["json", "summary"]);
237
+ var DynamoiListArtistsInputSchema = z2.object({
238
+ cursor: z2.string().optional(),
239
+ limit: z2.number().int().min(1).max(50).optional()
240
+ });
241
+ var DynamoiSearchInputSchema = z2.object({
242
+ cursor: z2.string().optional(),
243
+ limit: z2.number().int().min(1).max(50).optional(),
244
+ query: z2.string().trim().optional(),
245
+ type: z2.enum(["artist", "campaign", "smartlink"]).optional()
246
+ });
247
+ var DynamoiGetArtistInputSchema = z2.object({
248
+ artistId: z2.string().uuid()
249
+ });
250
+ var DynamoiListCampaignsInputSchema = z2.object({
251
+ artistId: z2.string().uuid(),
252
+ cursor: z2.string().optional(),
253
+ format: ToolFormatSchema.optional(),
254
+ limit: z2.number().int().min(1).max(50).optional(),
255
+ status: z2.string().trim().optional()
256
+ });
257
+ var DynamoiGetCampaignInputSchema = z2.object({
258
+ campaignId: z2.string().uuid()
259
+ });
260
+ var DateRangeSchema = z2.object({
261
+ end: z2.string().regex(/^\d{4}-\d{2}-\d{2}$/),
262
+ start: z2.string().regex(/^\d{4}-\d{2}-\d{2}$/)
263
+ });
264
+ var DynamoiGetCampaignAnalyticsInputSchema = z2.object({
265
+ campaignId: z2.string().uuid(),
266
+ dateRange: DateRangeSchema.optional(),
267
+ format: ToolFormatSchema.optional()
268
+ });
269
+ var DynamoiGetBillingInputSchema = z2.object({
270
+ artistId: z2.string().uuid()
271
+ });
272
+ var DynamoiGetPlatformStatusInputSchema = z2.object({
273
+ artistId: z2.string().uuid()
274
+ });
275
+ var DynamoiPauseCampaignInputSchema = z2.object({
276
+ campaignId: z2.string().uuid()
277
+ });
278
+ var DynamoiResumeCampaignInputSchema = z2.object({
279
+ campaignId: z2.string().uuid()
280
+ });
281
+ var DynamoiUpdateBudgetInputSchema = z2.object({
282
+ budgetAmount: z2.number().finite().positive(),
283
+ campaignId: z2.string().uuid(),
284
+ endDate: z2.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional()
285
+ });
286
+ var LocationTargetSchema = z2.object({
287
+ code: z2.string().min(1),
288
+ name: z2.string().min(1)
289
+ });
290
+ var DynamoiListMediaAssetsInputSchema = z2.object({
291
+ artistId: z2.string().uuid(),
292
+ cursor: z2.string().optional(),
293
+ limit: z2.number().int().min(1).max(50).optional()
294
+ });
295
+ var DynamoiLaunchCampaignInputSchema = z2.object({
296
+ // Creative
297
+ adCopy: z2.string().trim().optional(),
298
+ appleMusicUrl: z2.string().trim().min(1).optional(),
299
+ artistId: z2.string().uuid(),
300
+ // Budget
301
+ budgetAmount: z2.number().finite().positive(),
302
+ budgetSplits: z2.record(
303
+ z2.enum(["META", "GOOGLE"]),
304
+ z2.number().int().min(0).max(100)
305
+ ),
306
+ budgetType: z2.enum(["DAILY", "TOTAL"]),
307
+ campaignType: z2.enum(["SMART_CAMPAIGN", "YOUTUBE"]),
308
+ // Idempotency (client-generated UUID)
309
+ clientRequestId: z2.string().uuid(),
310
+ // Content
311
+ contentTitle: z2.string().trim().min(1),
312
+ contentType: z2.enum(["TRACK", "ALBUM", "PLAYLIST", "VIDEO"]),
313
+ endDate: z2.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
314
+ // Targeting
315
+ locationTargets: z2.array(LocationTargetSchema).optional(),
316
+ // Smart Campaign creative selection (existing assets only in Phase 3)
317
+ mediaAssetIds: z2.array(z2.string().uuid()).optional(),
318
+ spotifyUrl: z2.string().trim().min(1).optional(),
319
+ useAiGeneratedCopy: z2.boolean().optional(),
320
+ youtubeVideoId: z2.string().trim().min(1).optional()
321
+ }).superRefine((data, ctx) => {
322
+ if (data.budgetType === "TOTAL" && !data.endDate) {
323
+ ctx.addIssue({
324
+ code: "custom",
325
+ message: "endDate is required when budgetType is TOTAL",
326
+ path: ["endDate"]
327
+ });
328
+ }
329
+ const sum = Object.values(data.budgetSplits ?? {}).reduce(
330
+ (acc, v) => acc + (Number.isFinite(v) ? v : 0),
331
+ 0
332
+ );
333
+ if (!(sum > 0)) {
334
+ ctx.addIssue({
335
+ code: "custom",
336
+ message: "budgetSplits must allocate at least one platform",
337
+ path: ["budgetSplits"]
338
+ });
339
+ }
340
+ if (sum > 0 && Math.abs(sum - 100) > 0.01) {
341
+ ctx.addIssue({
342
+ code: "custom",
343
+ message: "budgetSplits must sum to 100",
344
+ path: ["budgetSplits"]
345
+ });
346
+ }
347
+ if (data.campaignType === "SMART_CAMPAIGN") {
348
+ if (!data.spotifyUrl) {
349
+ ctx.addIssue({
350
+ code: "custom",
351
+ message: "spotifyUrl is required for SMART_CAMPAIGN",
352
+ path: ["spotifyUrl"]
353
+ });
354
+ }
355
+ if (!data.mediaAssetIds || data.mediaAssetIds.length === 0) {
356
+ ctx.addIssue({
357
+ code: "custom",
358
+ message: "mediaAssetIds is required for SMART_CAMPAIGN",
359
+ path: ["mediaAssetIds"]
360
+ });
361
+ }
362
+ if (!("META" in data.budgetSplits) || data.budgetSplits.META <= 0) {
363
+ ctx.addIssue({
364
+ code: "custom",
365
+ message: "SMART_CAMPAIGN requires a META budget split > 0",
366
+ path: ["budgetSplits", "META"]
367
+ });
368
+ }
369
+ if (data.budgetSplits.GOOGLE && data.budgetSplits.GOOGLE > 0) {
370
+ ctx.addIssue({
371
+ code: "custom",
372
+ message: "SMART_CAMPAIGN does not support GOOGLE budget splits",
373
+ path: ["budgetSplits", "GOOGLE"]
374
+ });
375
+ }
376
+ }
377
+ if (data.campaignType === "YOUTUBE") {
378
+ if (!data.youtubeVideoId) {
379
+ ctx.addIssue({
380
+ code: "custom",
381
+ message: "youtubeVideoId is required for YOUTUBE",
382
+ path: ["youtubeVideoId"]
383
+ });
384
+ }
385
+ if (data.contentType !== "VIDEO") {
386
+ ctx.addIssue({
387
+ code: "custom",
388
+ message: "contentType must be VIDEO for YOUTUBE",
389
+ path: ["contentType"]
390
+ });
391
+ }
392
+ if (!("GOOGLE" in data.budgetSplits) || data.budgetSplits.GOOGLE <= 0) {
393
+ ctx.addIssue({
394
+ code: "custom",
395
+ message: "YOUTUBE requires a GOOGLE budget split > 0",
396
+ path: ["budgetSplits", "GOOGLE"]
397
+ });
398
+ }
399
+ if (data.budgetSplits.META && data.budgetSplits.META > 0) {
400
+ ctx.addIssue({
401
+ code: "custom",
402
+ message: "YOUTUBE does not support META budget splits",
403
+ path: ["budgetSplits", "META"]
404
+ });
405
+ }
406
+ }
407
+ });
408
+ var PHASE_1_TOOL_DEFINITIONS = [
409
+ {
410
+ description: "List all music artists and YouTube channels the user manages. Returns each artist's subscription tier, billing status, active campaign count, and the user's role.",
411
+ destructiveHint: false,
412
+ name: "dynamoi_list_artists",
413
+ openWorldHint: false,
414
+ readOnlyHint: true,
415
+ schema: DynamoiListArtistsInputSchema
416
+ },
417
+ {
418
+ description: "Search across artists, ad campaigns, and smart links by name or URL. Find a specific Spotify release, YouTube campaign, or artist profile.",
419
+ destructiveHint: false,
420
+ name: "dynamoi_search",
421
+ openWorldHint: false,
422
+ readOnlyHint: true,
423
+ schema: DynamoiSearchInputSchema
424
+ },
425
+ {
426
+ description: "Get a music artist or YouTube channel profile \u2014 connected platforms (Spotify, Meta, YouTube), subscription tier, billing status, and whether they're ready to launch campaigns.",
427
+ destructiveHint: false,
428
+ name: "dynamoi_get_artist",
429
+ openWorldHint: false,
430
+ readOnlyHint: true,
431
+ schema: DynamoiGetArtistInputSchema
432
+ },
433
+ {
434
+ description: "List ad campaigns for an artist \u2014 each campaign's content title, type (Smart Campaign for Spotify or YouTube for channel growth), budget, status, and platforms. Supports status filtering and pagination.",
435
+ destructiveHint: false,
436
+ name: "dynamoi_list_campaigns",
437
+ openWorldHint: false,
438
+ readOnlyHint: true,
439
+ schema: DynamoiListCampaignsInputSchema
440
+ },
441
+ {
442
+ description: "Get full details for a campaign \u2014 budget, targeting countries, per-platform status for Meta and Google, smart link URL, and any blocked reasons with suggested next actions.",
443
+ destructiveHint: false,
444
+ name: "dynamoi_get_campaign",
445
+ openWorldHint: false,
446
+ readOnlyHint: true,
447
+ schema: DynamoiGetCampaignInputSchema
448
+ },
449
+ {
450
+ description: "Get performance analytics for a campaign \u2014 impressions, clicks, ad spend, CPC, CPM, and CTR. Optionally filter by date range. Returns per-platform breakdowns for Meta Ads and Google Ads.",
451
+ destructiveHint: false,
452
+ name: "dynamoi_get_campaign_analytics",
453
+ openWorldHint: false,
454
+ readOnlyHint: true,
455
+ schema: DynamoiGetCampaignAnalyticsInputSchema
456
+ },
457
+ {
458
+ description: "Get an artist's billing summary \u2014 subscription tier, ad credit balance, billing status, and recent spend. Shows remaining credits and campaign usage for the current period.",
459
+ destructiveHint: false,
460
+ name: "dynamoi_get_billing",
461
+ openWorldHint: false,
462
+ readOnlyHint: true,
463
+ schema: DynamoiGetBillingInputSchema
464
+ },
465
+ {
466
+ description: "Check connection health for Spotify, Meta (Facebook/Instagram), and YouTube. Shows connection status, token expiry, and what steps remain before campaigns can launch on each platform.",
467
+ destructiveHint: false,
468
+ name: "dynamoi_get_platform_status",
469
+ openWorldHint: false,
470
+ readOnlyHint: true,
471
+ schema: DynamoiGetPlatformStatusInputSchema
472
+ }
473
+ ];
474
+ var PHASE_2_TOOL_DEFINITIONS = [
475
+ {
476
+ description: "Pause a running campaign, stopping ad delivery on Meta (Facebook/Instagram) and/or Google (YouTube). Returns per-platform results.",
477
+ destructiveHint: false,
478
+ name: "dynamoi_pause_campaign",
479
+ openWorldHint: true,
480
+ readOnlyHint: false,
481
+ schema: DynamoiPauseCampaignInputSchema
482
+ },
483
+ {
484
+ description: "Resume a paused campaign, restarting ad delivery on Meta and/or Google. Returns per-platform results.",
485
+ destructiveHint: false,
486
+ name: "dynamoi_resume_campaign",
487
+ openWorldHint: true,
488
+ readOnlyHint: false,
489
+ schema: DynamoiResumeCampaignInputSchema
490
+ },
491
+ {
492
+ description: "Change a campaign's daily or total budget amount in USD. For total-budget campaigns, the end date can also be updated. Cannot switch between daily and total budget types.",
493
+ destructiveHint: false,
494
+ name: "dynamoi_update_budget",
495
+ openWorldHint: true,
496
+ readOnlyHint: false,
497
+ schema: DynamoiUpdateBudgetInputSchema
498
+ }
499
+ ];
500
+ var PHASE_3_TOOL_DEFINITIONS = [
501
+ {
502
+ description: "List an artist's uploaded creative assets (images and videos) available for campaign launches. Use this to select media before launching a Smart Campaign.",
503
+ destructiveHint: false,
504
+ name: "dynamoi_list_media_assets",
505
+ openWorldHint: false,
506
+ readOnlyHint: true,
507
+ schema: DynamoiListMediaAssetsInputSchema
508
+ },
509
+ {
510
+ description: "Launch a new campaign to promote a Spotify release (track, album, or playlist via Meta Ads) or grow a YouTube channel (via Google Ads with AdSense revenue optimization). Provide a client-generated request ID for safe retries.",
511
+ destructiveHint: false,
512
+ name: "dynamoi_launch_campaign",
513
+ openWorldHint: true,
514
+ readOnlyHint: false,
515
+ schema: DynamoiLaunchCampaignInputSchema
516
+ }
517
+ ];
518
+
519
+ // src/server/create-server.ts
520
+ function asTextResult(envelope) {
521
+ return {
522
+ content: [{ text: JSON.stringify(envelope), type: "text" }],
523
+ structuredContent: envelope
524
+ };
525
+ }
526
+ function createDynamoiMcpServer(options) {
527
+ const server = new McpServer(
528
+ {
529
+ name: "dynamoi",
530
+ version: DYNAMOI_MCP_VERSION,
531
+ websiteUrl: "https://dynamoi.com"
532
+ },
533
+ { instructions: DYNAMOI_MCP_INSTRUCTIONS }
534
+ );
535
+ for (const def of [
536
+ ...PHASE_1_TOOL_DEFINITIONS,
537
+ ...PHASE_2_TOOL_DEFINITIONS,
538
+ ...PHASE_3_TOOL_DEFINITIONS
539
+ ]) {
540
+ server.registerTool(
541
+ def.name,
542
+ {
543
+ annotations: {
544
+ destructiveHint: def.destructiveHint,
545
+ openWorldHint: def.openWorldHint,
546
+ readOnlyHint: def.readOnlyHint
547
+ },
548
+ description: def.description,
549
+ inputSchema: def.schema,
550
+ title: def.name
551
+ },
552
+ async (input) => {
553
+ switch (def.name) {
554
+ case "dynamoi_list_artists":
555
+ return asTextResult(await options.adapter.listArtists(input));
556
+ case "dynamoi_search":
557
+ return asTextResult(await options.adapter.search(input));
558
+ case "dynamoi_get_artist":
559
+ return asTextResult(await options.adapter.getArtist(input));
560
+ case "dynamoi_list_campaigns":
561
+ return asTextResult(await options.adapter.listCampaigns(input));
562
+ case "dynamoi_get_campaign":
563
+ return asTextResult(await options.adapter.getCampaign(input));
564
+ case "dynamoi_get_campaign_analytics":
565
+ return asTextResult(
566
+ await options.adapter.getCampaignAnalytics(input)
567
+ );
568
+ case "dynamoi_get_billing":
569
+ return asTextResult(await options.adapter.getBilling(input));
570
+ case "dynamoi_get_platform_status":
571
+ return asTextResult(await options.adapter.getPlatformStatus(input));
572
+ case "dynamoi_pause_campaign":
573
+ return asTextResult(await options.adapter.pauseCampaign(input));
574
+ case "dynamoi_resume_campaign":
575
+ return asTextResult(await options.adapter.resumeCampaign(input));
576
+ case "dynamoi_update_budget":
577
+ return asTextResult(await options.adapter.updateBudget(input));
578
+ case "dynamoi_list_media_assets":
579
+ return asTextResult(await options.adapter.listMediaAssets(input));
580
+ case "dynamoi_launch_campaign":
581
+ return asTextResult(await options.adapter.launchCampaign(input));
582
+ default:
583
+ return asTextResult({
584
+ message: "Unknown tool",
585
+ status: "error"
586
+ });
587
+ }
588
+ }
589
+ );
590
+ }
591
+ registerDynamoiPrompts(server);
592
+ server.registerResource(
593
+ "platform-pricing",
594
+ "dynamoi://platform/pricing",
595
+ {
596
+ description: "Dynamoi pricing, activation bonus, ad credit structure, and campaign budget minimums.",
597
+ mimeType: "application/json",
598
+ title: "Pricing"
599
+ },
600
+ async (uri) => ({
601
+ contents: [
602
+ {
603
+ mimeType: "application/json",
604
+ text: JSON.stringify({
605
+ activationBonus: {
606
+ amountUsd: 600,
607
+ note: "100% match on first month \u2014 pay $300, get $600 ad credit"
608
+ },
609
+ budgetMinimums: {
610
+ smartCampaign: {
611
+ dailyUsd: 10,
612
+ note: "Meta Ads for Spotify promotion",
613
+ totalUsd: 100
614
+ },
615
+ youtube: {
616
+ dailyUsd: 10,
617
+ note: "Google Ads for YouTube channel growth",
618
+ totalUsd: 50
619
+ }
620
+ },
621
+ creditRollover: "Credits roll over for 12 months",
622
+ includes: "Unlimited team seats, unlimited artists, white-glove support, free smart link landing pages",
623
+ noContracts: true,
624
+ tiers: [
625
+ {
626
+ name: "Plus",
627
+ note: "100% Ad Credit. No agency fees.",
628
+ priceUsdMonthly: 300
629
+ }
630
+ ]
631
+ }),
632
+ uri: uri.href
633
+ }
634
+ ]
635
+ })
636
+ );
637
+ server.registerResource(
638
+ "platform-content-types",
639
+ "dynamoi://platform/content-types",
640
+ { mimeType: "application/json", title: "Content Types" },
641
+ async (uri) => ({
642
+ contents: [
643
+ {
644
+ mimeType: "application/json",
645
+ text: JSON.stringify({
646
+ campaignTypes: {
647
+ SMART_CAMPAIGN: ["TRACK", "ALBUM", "PLAYLIST"],
648
+ YOUTUBE: ["VIDEO"]
649
+ },
650
+ contentTypes: ["TRACK", "ALBUM", "PLAYLIST", "VIDEO"]
651
+ }),
652
+ uri: uri.href
653
+ }
654
+ ]
655
+ })
656
+ );
657
+ server.registerResource(
658
+ "platform-campaign-statuses",
659
+ "dynamoi://platform/campaign-statuses",
660
+ { mimeType: "application/json", title: "Campaign Statuses" },
661
+ async (uri) => ({
662
+ contents: [
663
+ {
664
+ mimeType: "application/json",
665
+ text: JSON.stringify({
666
+ statuses: [
667
+ "AWAITING_SMART_LINK",
668
+ "CONTENT_VALIDATION",
669
+ "DEPLOYING",
670
+ "READY_FOR_REVIEW",
671
+ "ACTIVE",
672
+ "PAUSED",
673
+ "SUBSCRIPTION_PAUSED",
674
+ "FAILED",
675
+ "ARCHIVED",
676
+ "ENDED"
677
+ ]
678
+ }),
679
+ uri: uri.href
680
+ }
681
+ ]
682
+ })
683
+ );
684
+ server.registerResource(
685
+ "artist-resource",
686
+ new ResourceTemplate("artist://{artistId}", {
687
+ list: async () => ({ resources: [] })
688
+ }),
689
+ { mimeType: "application/json", title: "Artist" },
690
+ async (uri, variables) => {
691
+ const artistId = variables["artistId"];
692
+ const parsed = z3.string().uuid().safeParse(artistId);
693
+ if (!parsed.success) {
694
+ return {
695
+ contents: [
696
+ {
697
+ mimeType: "application/json",
698
+ text: JSON.stringify({
699
+ message: "Invalid artistId",
700
+ status: "error"
701
+ }),
702
+ uri: uri.href
703
+ }
704
+ ]
705
+ };
706
+ }
707
+ const envelope = await options.adapter.getArtist({
708
+ artistId: parsed.data
709
+ });
710
+ return {
711
+ contents: [
712
+ {
713
+ mimeType: "application/json",
714
+ text: JSON.stringify(envelope),
715
+ uri: uri.href
716
+ }
717
+ ]
718
+ };
719
+ }
720
+ );
721
+ server.registerResource(
722
+ "campaign-resource",
723
+ new ResourceTemplate("campaign://{campaignId}", {
724
+ list: async () => ({ resources: [] })
725
+ }),
726
+ { mimeType: "application/json", title: "Campaign" },
727
+ async (uri, variables) => {
728
+ const campaignId = variables["campaignId"];
729
+ const parsed = z3.string().uuid().safeParse(campaignId);
730
+ if (!parsed.success) {
731
+ return {
732
+ contents: [
733
+ {
734
+ mimeType: "application/json",
735
+ text: JSON.stringify({
736
+ message: "Invalid campaignId",
737
+ status: "error"
738
+ }),
739
+ uri: uri.href
740
+ }
741
+ ]
742
+ };
743
+ }
744
+ const envelope = await options.adapter.getCampaign({
745
+ campaignId: parsed.data
746
+ });
747
+ return {
748
+ contents: [
749
+ {
750
+ mimeType: "application/json",
751
+ text: JSON.stringify(envelope),
752
+ uri: uri.href
753
+ }
754
+ ]
755
+ };
756
+ }
757
+ );
758
+ return server;
759
+ }
760
+
761
+ // src/transport/http.ts
762
+ import { randomUUID } from "crypto";
763
+ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
764
+ import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
765
+ var transports = /* @__PURE__ */ new Map();
766
+ var SESSION_TTL_MS = 30 * 60 * 1e3;
767
+ var MAX_SESSIONS = 250;
768
+ function closeTransportBestEffort(entry) {
769
+ void entry.transport.close().catch(() => {
770
+ });
771
+ }
772
+ function cleanupTransports(nowMs) {
773
+ for (const [sid, entry] of transports.entries()) {
774
+ const expired = nowMs - entry.lastUsedAtMs > SESSION_TTL_MS;
775
+ if (expired) {
776
+ closeTransportBestEffort(entry);
777
+ transports.delete(sid);
778
+ }
779
+ }
780
+ if (transports.size > MAX_SESSIONS) {
781
+ const entries = Array.from(transports.entries()).sort(
782
+ (a, b) => a[1].lastUsedAtMs - b[1].lastUsedAtMs
783
+ );
784
+ const over = transports.size - MAX_SESSIONS;
785
+ for (let i = 0; i < over; i += 1) {
786
+ const sid = entries[i]?.[0];
787
+ if (sid) {
788
+ const entry = entries[i]?.[1];
789
+ if (entry) {
790
+ closeTransportBestEffort(entry);
791
+ }
792
+ transports.delete(sid);
793
+ }
794
+ }
795
+ }
796
+ }
797
+ function getHeader(request, name) {
798
+ const value = request.headers.get(name);
799
+ return value && value.trim().length > 0 ? value : null;
800
+ }
801
+ function jsonRpcSessionNotFound() {
802
+ return new Response(
803
+ JSON.stringify({
804
+ error: { code: -32001, message: "Session not found" },
805
+ id: null,
806
+ jsonrpc: "2.0"
807
+ }),
808
+ {
809
+ headers: { "content-type": "application/json" },
810
+ status: 404
811
+ }
812
+ );
813
+ }
814
+ async function handleMcpHttpRequest(options) {
815
+ const nowMs = Date.now();
816
+ cleanupTransports(nowMs);
817
+ const sessionId = getHeader(options.request, "mcp-session-id");
818
+ const existing = sessionId ? transports.get(sessionId) : void 0;
819
+ if (existing) {
820
+ if (existing.contextKey !== options.sessionContextKey) {
821
+ closeTransportBestEffort(existing);
822
+ transports.delete(sessionId);
823
+ return jsonRpcSessionNotFound();
824
+ }
825
+ existing.lastUsedAtMs = nowMs;
826
+ const response = await existing.transport.handleRequest(options.request, {
827
+ parsedBody: options.parsedBody
828
+ });
829
+ if (options.request.method.toUpperCase() === "DELETE" && sessionId) {
830
+ closeTransportBestEffort(existing);
831
+ transports.delete(sessionId);
832
+ }
833
+ return response;
834
+ }
835
+ const isInit = isInitializeRequest(options.parsedBody);
836
+ const transport = new WebStandardStreamableHTTPServerTransport({
837
+ onsessioninitialized: (sid) => {
838
+ transports.set(sid, {
839
+ contextKey: options.sessionContextKey,
840
+ createdAtMs: nowMs,
841
+ lastUsedAtMs: nowMs,
842
+ transport
843
+ });
844
+ cleanupTransports(Date.now());
845
+ },
846
+ sessionIdGenerator: isInit ? () => randomUUID() : void 0
847
+ });
848
+ const server = options.createServer();
849
+ await server.connect(transport);
850
+ return transport.handleRequest(options.request, {
851
+ parsedBody: options.parsedBody
852
+ });
853
+ }
854
+ export {
855
+ DateRangeSchema,
856
+ DynamoiGetArtistInputSchema,
857
+ DynamoiGetBillingInputSchema,
858
+ DynamoiGetCampaignAnalyticsInputSchema,
859
+ DynamoiGetCampaignInputSchema,
860
+ DynamoiGetPlatformStatusInputSchema,
861
+ DynamoiLaunchCampaignInputSchema,
862
+ DynamoiListArtistsInputSchema,
863
+ DynamoiListCampaignsInputSchema,
864
+ DynamoiListMediaAssetsInputSchema,
865
+ DynamoiPauseCampaignInputSchema,
866
+ DynamoiResumeCampaignInputSchema,
867
+ DynamoiSearchInputSchema,
868
+ DynamoiUpdateBudgetInputSchema,
869
+ PHASE_1_TOOL_DEFINITIONS,
870
+ PHASE_2_TOOL_DEFINITIONS,
871
+ PHASE_3_TOOL_DEFINITIONS,
872
+ ToolFormatSchema,
873
+ buildProtectedResourceMetadata,
874
+ buildWwwAuthenticateHeader,
875
+ createDynamoiMcpServer,
876
+ handleMcpHttpRequest,
877
+ verifyAccessToken
878
+ };
879
+ //# sourceMappingURL=index.js.map