@mkterswingman/5mghost-yonder 0.0.38 → 0.0.40

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.
@@ -0,0 +1,225 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { PATHS } from "./utils/config.js";
5
+ const PRODUCT = "5mghost-yonder";
6
+ const PRODUCT_VERSION = "0.0.40";
7
+ const MAX_ERROR_CODE_CHARS = 64;
8
+ export class ToolTelemetryClient {
9
+ config;
10
+ tokenManager;
11
+ fetchImpl;
12
+ configuredInstallId;
13
+ persistedInstallId;
14
+ logger;
15
+ constructor(config, tokenManager, deps = {}) {
16
+ this.config = config;
17
+ this.tokenManager = tokenManager;
18
+ this.fetchImpl = deps.fetchImpl ?? fetch;
19
+ this.configuredInstallId = deps.installId;
20
+ this.logger = deps.logger ?? { warn: () => { } };
21
+ }
22
+ recordToolCall(input) {
23
+ if (!this.config.telemetry_enabled) {
24
+ return;
25
+ }
26
+ const event = buildToolTelemetryEvent({
27
+ toolName: input.toolName,
28
+ startedAtMs: input.startedAtMs,
29
+ installId: this.getInstallId(),
30
+ result: input.result,
31
+ thrown: input.thrown,
32
+ });
33
+ setImmediate(() => {
34
+ void this.send(event);
35
+ });
36
+ }
37
+ getInstallId() {
38
+ if (this.configuredInstallId) {
39
+ return this.configuredInstallId;
40
+ }
41
+ this.persistedInstallId ??= getOrCreateInstallId();
42
+ return this.persistedInstallId;
43
+ }
44
+ async send(event) {
45
+ if (!isSameOrigin(this.config.telemetry_endpoint_url, this.config.auth_url)) {
46
+ this.logger.warn("yt_mcp_telemetry_same_origin_blocked", {
47
+ product: PRODUCT,
48
+ tool_name: event.tool_name,
49
+ });
50
+ return;
51
+ }
52
+ try {
53
+ const token = await this.tokenManager.getValidToken();
54
+ if (!token) {
55
+ return;
56
+ }
57
+ const controller = new AbortController();
58
+ const timeout = setTimeout(() => controller.abort(), this.config.telemetry_timeout_ms);
59
+ timeout.unref?.();
60
+ try {
61
+ const response = await this.fetchImpl(this.config.telemetry_endpoint_url, {
62
+ method: "POST",
63
+ headers: {
64
+ Authorization: `Bearer ${token}`,
65
+ "Content-Type": "application/json",
66
+ },
67
+ body: JSON.stringify({ events: [event] }),
68
+ signal: controller.signal,
69
+ });
70
+ if (!response.ok) {
71
+ this.logger.warn("yt_mcp_telemetry_send_failed", {
72
+ product: PRODUCT,
73
+ tool_name: event.tool_name,
74
+ status_code: response.status,
75
+ });
76
+ }
77
+ }
78
+ finally {
79
+ clearTimeout(timeout);
80
+ }
81
+ }
82
+ catch (error) {
83
+ this.logger.warn("yt_mcp_telemetry_send_failed", {
84
+ product: PRODUCT,
85
+ tool_name: event.tool_name,
86
+ code: "TELEMETRY_NETWORK_ERROR",
87
+ message: error instanceof Error ? error.name : "UnknownError",
88
+ });
89
+ }
90
+ }
91
+ }
92
+ export function buildToolTelemetryEvent(input) {
93
+ const durationMs = Math.max(0, Math.round(Date.now() - input.startedAtMs));
94
+ const error = classifyTelemetryError(input.result, input.thrown);
95
+ const base = {
96
+ schema_version: 1,
97
+ event_id: `${PRODUCT}-${Date.now()}-${randomUUID()}`,
98
+ occurred_at: new Date().toISOString(),
99
+ product: PRODUCT,
100
+ product_version: PRODUCT_VERSION,
101
+ install_id: input.installId,
102
+ event_type: "tool_call",
103
+ tool_name: input.toolName,
104
+ duration_ms: durationMs,
105
+ };
106
+ if (!error) {
107
+ return {
108
+ ...base,
109
+ outcome: "success",
110
+ };
111
+ }
112
+ return {
113
+ ...base,
114
+ outcome: "failure",
115
+ error_kind: error.kind,
116
+ error_code: error.code,
117
+ error_message: error.message,
118
+ };
119
+ }
120
+ export function classifyTelemetryError(result, thrown) {
121
+ if (thrown) {
122
+ return {
123
+ kind: "internal",
124
+ code: "INTERNAL_ERROR",
125
+ message: "Tool handler threw an unexpected error",
126
+ };
127
+ }
128
+ if (!result?.isError) {
129
+ return null;
130
+ }
131
+ const error = readStructuredError(result.structuredContent);
132
+ const code = normalizeErrorCode(error.code);
133
+ return {
134
+ kind: classifyErrorKind(code),
135
+ code,
136
+ message: safeErrorMessage(code),
137
+ };
138
+ }
139
+ function readStructuredError(value) {
140
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
141
+ return { code: null };
142
+ }
143
+ const error = value.error;
144
+ if (!error || typeof error !== "object" || Array.isArray(error)) {
145
+ return { code: null };
146
+ }
147
+ const record = error;
148
+ return {
149
+ code: typeof record.code === "string" ? record.code : null,
150
+ };
151
+ }
152
+ function normalizeErrorCode(code) {
153
+ if (!code) {
154
+ return "UNKNOWN_ERROR";
155
+ }
156
+ const normalized = code.toUpperCase().replace(/[^A-Z0-9_.:-]/g, "_").slice(0, MAX_ERROR_CODE_CHARS);
157
+ return normalized || "UNKNOWN_ERROR";
158
+ }
159
+ function classifyErrorKind(code) {
160
+ if (code.includes("RATE_LIMIT") || code === "HTTP_429") {
161
+ return "rate_limit";
162
+ }
163
+ if (code.startsWith("AUTH") || code.includes("COOKIE") || code === "SIGN_IN_REQUIRED") {
164
+ return "auth";
165
+ }
166
+ if (code === "INVALID_INPUT" || code.includes("VALIDATION")) {
167
+ return "validation";
168
+ }
169
+ if (code.startsWith("REMOTE") || code.startsWith("UPSTREAM") || code.startsWith("HTTP_") || code === "NETWORK_ERROR") {
170
+ return "upstream";
171
+ }
172
+ return "internal";
173
+ }
174
+ function safeErrorMessage(code) {
175
+ const kind = classifyErrorKind(code);
176
+ if (kind === "rate_limit") {
177
+ return "Rate limit was reached";
178
+ }
179
+ if (kind === "auth") {
180
+ return "Authorization failed";
181
+ }
182
+ if (kind === "validation") {
183
+ return "Invalid input";
184
+ }
185
+ if (kind === "upstream") {
186
+ return "Remote tool request failed";
187
+ }
188
+ if (code === "NO_SUBTITLES") {
189
+ return "Requested subtitles were not found";
190
+ }
191
+ return "Tool call failed";
192
+ }
193
+ function isSameOrigin(endpoint, authUrl) {
194
+ try {
195
+ return new URL(endpoint).origin === new URL(authUrl).origin;
196
+ }
197
+ catch {
198
+ return false;
199
+ }
200
+ }
201
+ function getOrCreateInstallId() {
202
+ const path = join(PATHS.configDir, "telemetry.json");
203
+ try {
204
+ if (existsSync(path)) {
205
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
206
+ if (typeof parsed.install_id === "string" && parsed.install_id.trim()) {
207
+ return parsed.install_id.trim();
208
+ }
209
+ }
210
+ }
211
+ catch {
212
+ // Why: telemetry must never block MCP tool registration on local state corruption.
213
+ }
214
+ const installId = `local-${randomUUID()}`;
215
+ try {
216
+ mkdirSync(PATHS.configDir, { recursive: true });
217
+ const tempPath = `${path}.tmp`;
218
+ writeFileSync(tempPath, JSON.stringify({ install_id: installId }, null, 2), { encoding: "utf8", mode: 0o600 });
219
+ renameSync(tempPath, path);
220
+ }
221
+ catch {
222
+ // Why: a read-only home directory should disable persistence, not MCP tools.
223
+ }
224
+ return installId;
225
+ }
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { YOUTUBE_TOOL_CONTRACTS } from "../contracts/youtubeToolContracts.js";
2
3
  function toolErr(code, message) {
3
4
  const payload = { status: "failed", error: { code, message } };
4
5
  return {
@@ -69,9 +70,8 @@ function createRemoteTool(server, def, tokenManager, apiUrl) {
69
70
  }
70
71
  });
71
72
  }
72
- const REMOTE_TOOLS = [
73
- {
74
- name: "search_videos",
73
+ const REMOTE_TOOL_META = {
74
+ search_videos: {
75
75
  description: "Search YouTube videos by keyword. Supports up to 300 results.",
76
76
  schema: {
77
77
  query: z.string().min(1),
@@ -87,42 +87,32 @@ const REMOTE_TOOLS = [
87
87
  ])
88
88
  .optional(),
89
89
  },
90
- remotePath: "api/search",
91
90
  },
92
- {
93
- name: "get_video_stats",
91
+ get_video_stats: {
94
92
  description: "Get YouTube video stats in one request. Accepts up to 1000 video IDs/URLs.",
95
93
  schema: {
96
94
  videos: z.array(z.string().min(1)).min(1).max(1000),
97
95
  },
98
- remotePath: "api/video-stats/bulk",
99
96
  },
100
- {
101
- name: "start_video_stats_job",
97
+ start_video_stats_job: {
102
98
  description: "Start an async YouTube video stats job. Accepts up to 1000 items.",
103
99
  schema: {
104
100
  videos: z.array(z.string().min(1)).min(1).max(1000),
105
101
  },
106
- remotePath: "api/video-stats/job/start",
107
102
  },
108
- {
109
- name: "poll_video_stats_job",
103
+ poll_video_stats_job: {
110
104
  description: "Poll job progress and get partial/final results for a job_id.",
111
105
  schema: {
112
106
  job_id: z.string().min(1),
113
107
  },
114
- remotePath: "api/video-stats/job/poll",
115
108
  },
116
- {
117
- name: "resume_video_stats_job",
109
+ resume_video_stats_job: {
118
110
  description: "Resume a previously partial job with a resume_token.",
119
111
  schema: {
120
112
  resume_token: z.string().min(1),
121
113
  },
122
- remotePath: "api/video-stats/job/resume",
123
114
  },
124
- {
125
- name: "get_trending",
115
+ get_trending: {
126
116
  description: "Get official YouTube mostPopular videos. Supports region/category filters.",
127
117
  schema: {
128
118
  region_code: z
@@ -132,38 +122,30 @@ const REMOTE_TOOLS = [
132
122
  category_id: z.string().min(1).max(64).optional(),
133
123
  max_results: z.number().int().min(1).max(300).optional(),
134
124
  },
135
- remotePath: "api/trending",
136
125
  },
137
- {
138
- name: "search_channels",
126
+ search_channels: {
139
127
  description: "Search YouTube channels by keyword for candidate discovery.",
140
128
  schema: {
141
129
  query: z.string().min(1).max(200),
142
130
  max_results: z.number().int().min(1).max(50).optional(),
143
131
  },
144
- remotePath: "api/channel/search",
145
132
  },
146
- {
147
- name: "get_channel_stats",
133
+ get_channel_stats: {
148
134
  description: "Get YouTube channel statistics for up to 50 channel inputs.",
149
135
  schema: {
150
136
  channels: z.array(z.string().min(1)).min(1).max(50).optional(),
151
137
  channel_ids: z.array(z.string().min(1)).min(1).max(50).optional(),
152
138
  },
153
- remotePath: "api/channel/stats",
154
139
  },
155
- {
156
- name: "list_channel_uploads",
140
+ list_channel_uploads: {
157
141
  description: "List videos uploaded by a YouTube channel. Supports up to 1000 results.",
158
142
  schema: {
159
143
  channel: z.string().min(1).optional(),
160
144
  channel_id: z.string().min(1).optional(),
161
145
  max_results: z.number().int().min(1).max(1000).optional(),
162
146
  },
163
- remotePath: "api/channel/uploads",
164
147
  },
165
- {
166
- name: "get_comments",
148
+ get_comments: {
167
149
  description: "Get comments for one YouTube video. max_comments up to 1000.",
168
150
  schema: {
169
151
  video: z.string().min(1),
@@ -173,46 +155,36 @@ const REMOTE_TOOLS = [
173
155
  replies_preview_per_comment: z.number().int().min(1).max(5).optional(),
174
156
  replies_preview_parent_limit: z.number().int().min(1).max(25).optional(),
175
157
  },
176
- remotePath: "api/comments/sync",
177
158
  },
178
- {
179
- name: "start_comments_job",
159
+ start_comments_job: {
180
160
  description: "Start a comments export job for one YouTube video.",
181
161
  schema: {
182
162
  video: z.string().min(1),
183
163
  max_comments: z.number().int().min(1).max(1000).optional(),
184
164
  order: z.enum(["time", "relevance"]).optional(),
185
165
  },
186
- remotePath: "api/comments/start",
187
166
  },
188
- {
189
- name: "poll_comments_job",
167
+ poll_comments_job: {
190
168
  description: "Check comments export job progress by job_id.",
191
169
  schema: {
192
170
  job_id: z.string().min(1),
193
171
  },
194
- remotePath: "api/comments/poll",
195
172
  },
196
- {
197
- name: "resume_comments_job",
173
+ resume_comments_job: {
198
174
  description: "Resume an unfinished comments export job.",
199
175
  schema: {
200
176
  resume_token: z.string().min(1),
201
177
  },
202
- remotePath: "api/comments/resume",
203
178
  },
204
- {
205
- name: "get_comment_replies",
179
+ get_comment_replies: {
206
180
  description: "Get 2nd-level replies for one top-level comment.",
207
181
  schema: {
208
182
  parent_comment_id: z.string().min(1),
209
183
  max_results: z.number().int().min(1).max(1000).optional(),
210
184
  page_token: z.string().min(1).optional(),
211
185
  },
212
- remotePath: "api/comments/replies",
213
186
  },
214
- {
215
- name: "get_quota_usage",
187
+ get_quota_usage: {
216
188
  description: "Get YouTube API quota usage for today or a specific date.",
217
189
  schema: {
218
190
  date: z
@@ -220,18 +192,27 @@ const REMOTE_TOOLS = [
220
192
  .regex(/^\d{4}-\d{2}-\d{2}$/)
221
193
  .optional(),
222
194
  },
223
- remotePath: "api/quota",
224
195
  },
225
- {
226
- name: "get_patch_notes",
196
+ get_patch_notes: {
227
197
  description: "Read server patch notes for latest MCP/API updates.",
228
198
  schema: {
229
199
  max_chars: z.number().int().min(500).max(50_000).optional(),
230
200
  },
231
- remotePath: "api/patch-notes",
232
- method: "GET",
233
201
  },
234
- ];
202
+ };
203
+ const REMOTE_TOOLS = YOUTUBE_TOOL_CONTRACTS.map((contract) => {
204
+ const meta = REMOTE_TOOL_META[contract.id];
205
+ if (!meta) {
206
+ throw new Error(`Missing remote tool metadata for contract id: ${contract.id}`);
207
+ }
208
+ return {
209
+ name: contract.remote_tool_name,
210
+ description: meta.description,
211
+ schema: meta.schema,
212
+ remotePath: contract.http_path.replace(/^\//, ""),
213
+ method: contract.http_method,
214
+ };
215
+ });
235
216
  export function registerRemoteTools(server, config, tokenManager) {
236
217
  for (const def of REMOTE_TOOLS) {
237
218
  createRemoteTool(server, def, tokenManager, config.api_url);
@@ -0,0 +1,22 @@
1
+ export declare const COOKIE_MISSING_MESSAGE = "No valid YouTube cookies found.\nPlease run in your terminal: yt-mcp setup-cookies";
2
+ export declare const COOKIE_EXPIRED_MESSAGE = "YouTube cookies have expired and auto-refresh failed.\nPlease run in your terminal: yt-mcp setup-cookies";
3
+ export declare const COOKIE_INVALID_MESSAGE = "YouTube rejected the current cookies and auto-refresh failed.\nPlease run in your terminal: yt-mcp setup-cookies";
4
+ export declare const SIGN_IN_REQUIRED_MESSAGE = "YouTube requested an additional sign-in confirmation and auto-refresh failed.\nPlease run in your terminal: yt-mcp setup-cookies";
5
+ export declare const RATE_LIMITED_MESSAGE = "The current YouTube session has been rate-limited. Wait and retry later.";
6
+ export declare const COOKIE_JOB_MESSAGE = "YouTube cookies are missing, expired, or invalid.\nPlease run in your terminal: yt-mcp setup-cookies";
7
+ export type CookieFailureCode = "COOKIES_INVALID" | "COOKIES_EXPIRED" | "SIGN_IN_REQUIRED" | "RATE_LIMITED";
8
+ export declare function tryRefreshSubtitleCookies(): Promise<boolean>;
9
+ export declare function isCookieFailureText(error?: string): boolean;
10
+ export declare function classifyYtDlpCookieFailure(stderr: string): {
11
+ code: CookieFailureCode;
12
+ message: string;
13
+ } | null;
14
+ export declare function toReadableSubtitleJobError(error: unknown): string;
15
+ export declare function ensureSubtitleCookiesReady(): Promise<{
16
+ ok: true;
17
+ } | {
18
+ ok: false;
19
+ code: "COOKIES_MISSING" | "COOKIES_EXPIRED";
20
+ toolMessage: string;
21
+ jobMessage: string;
22
+ }>;
@@ -0,0 +1,66 @@
1
+ import { PATHS } from "../../utils/config.js";
2
+ import { hasSIDCookies, areCookiesExpired } from "../../utils/cookies.js";
3
+ import { tryHeadlessRefresh } from "../../utils/cookieRefresh.js";
4
+ import { appendDiagnosticLog, classifyYtDlpFailure } from "../../utils/ytdlpFailures.js";
5
+ const COOKIE_SETUP_COMMAND = "yt-mcp setup-cookies";
6
+ export const COOKIE_MISSING_MESSAGE = `No valid YouTube cookies found.\nPlease run in your terminal: ${COOKIE_SETUP_COMMAND}`;
7
+ export const COOKIE_EXPIRED_MESSAGE = `YouTube cookies have expired and auto-refresh failed.\nPlease run in your terminal: ${COOKIE_SETUP_COMMAND}`;
8
+ export const COOKIE_INVALID_MESSAGE = `YouTube rejected the current cookies and auto-refresh failed.\nPlease run in your terminal: ${COOKIE_SETUP_COMMAND}`;
9
+ export const SIGN_IN_REQUIRED_MESSAGE = `YouTube requested an additional sign-in confirmation and auto-refresh failed.\nPlease run in your terminal: ${COOKIE_SETUP_COMMAND}`;
10
+ export const RATE_LIMITED_MESSAGE = "The current YouTube session has been rate-limited. Wait and retry later.";
11
+ export const COOKIE_JOB_MESSAGE = `YouTube cookies are missing, expired, or invalid.\nPlease run in your terminal: ${COOKIE_SETUP_COMMAND}`;
12
+ export async function tryRefreshSubtitleCookies() {
13
+ try {
14
+ return await tryHeadlessRefresh();
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ }
20
+ export function isCookieFailureText(error) {
21
+ if (!error) {
22
+ return false;
23
+ }
24
+ const normalized = error.toLowerCase();
25
+ return (normalized.includes("cookies_expired") ||
26
+ normalized.includes("cookie") ||
27
+ normalized.includes("sign in") ||
28
+ normalized.includes("login") ||
29
+ normalized.includes("not a bot"));
30
+ }
31
+ export function classifyYtDlpCookieFailure(stderr) {
32
+ const kind = classifyYtDlpFailure(stderr);
33
+ switch (kind) {
34
+ case "COOKIES_EXPIRED":
35
+ return { code: kind, message: COOKIE_EXPIRED_MESSAGE };
36
+ case "COOKIES_INVALID":
37
+ return { code: kind, message: COOKIE_INVALID_MESSAGE };
38
+ case "SIGN_IN_REQUIRED":
39
+ return { code: kind, message: SIGN_IN_REQUIRED_MESSAGE };
40
+ case "RATE_LIMITED":
41
+ return { code: kind, message: RATE_LIMITED_MESSAGE };
42
+ default:
43
+ return null;
44
+ }
45
+ }
46
+ export function toReadableSubtitleJobError(error) {
47
+ const message = error instanceof Error ? error.message : String(error);
48
+ return isCookieFailureText(message) ? COOKIE_JOB_MESSAGE : message;
49
+ }
50
+ export async function ensureSubtitleCookiesReady() {
51
+ const hasSession = hasSIDCookies(PATHS.cookiesTxt);
52
+ const expired = areCookiesExpired(PATHS.cookiesTxt);
53
+ if (hasSession && !expired) {
54
+ return { ok: true };
55
+ }
56
+ const refreshed = await tryRefreshSubtitleCookies();
57
+ if (refreshed && hasSIDCookies(PATHS.cookiesTxt) && !areCookiesExpired(PATHS.cookiesTxt)) {
58
+ return { ok: true };
59
+ }
60
+ return {
61
+ ok: false,
62
+ code: hasSession && expired ? "COOKIES_EXPIRED" : "COOKIES_MISSING",
63
+ toolMessage: hasSession && expired ? COOKIE_EXPIRED_MESSAGE : COOKIE_MISSING_MESSAGE,
64
+ jobMessage: appendDiagnosticLog(COOKIE_JOB_MESSAGE, undefined),
65
+ };
66
+ }
@@ -0,0 +1,24 @@
1
+ import { COOKIE_EXPIRED_MESSAGE, COOKIE_INVALID_MESSAGE, RATE_LIMITED_MESSAGE, SIGN_IN_REQUIRED_MESSAGE, type CookieFailureCode } from "./cookieSession.js";
2
+ export declare function downloadSubtitle(videoId: string, lang: string, format: string, options?: {
3
+ sourceUrl?: string;
4
+ outputDir?: string;
5
+ outputStem?: string;
6
+ targetFile?: string;
7
+ }): Promise<{
8
+ ok: boolean;
9
+ filePath?: string;
10
+ text?: string;
11
+ error?: string;
12
+ cookieFailureCode?: CookieFailureCode;
13
+ diagnosticLogPath?: string;
14
+ }>;
15
+ export declare function downloadSubtitlesForLanguages(input: {
16
+ videoId: string;
17
+ sourceUrl?: string;
18
+ languages: string[];
19
+ formats: string[];
20
+ subtitlesDir: string;
21
+ skipMissingLanguages?: boolean;
22
+ onProgress?: (completed: number, total: number) => void;
23
+ }): Promise<Record<string, string[]>>;
24
+ export { COOKIE_EXPIRED_MESSAGE, COOKIE_INVALID_MESSAGE, SIGN_IN_REQUIRED_MESSAGE, RATE_LIMITED_MESSAGE };