source-reference-utils.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. export function readRecord(value: unknown): Record<string, unknown> | undefined {
  2. return typeof value === 'object' && value !== null && !Array.isArray(value)
  3. ? (value as Record<string, unknown>)
  4. : undefined;
  5. }
  6. export function readNonEmptyString(value: unknown): string | undefined {
  7. return typeof value === 'string' && value.trim() ? value.trim() : undefined;
  8. }
  9. export function safeHttpUrl(value: string | undefined): string | undefined {
  10. if (!value) return undefined;
  11. try {
  12. const url = new URL(value);
  13. return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : undefined;
  14. } catch {
  15. return undefined;
  16. }
  17. }
  18. export function escapeMarkdownLabel(value: string): string {
  19. return value.replaceAll('\\', '\\\\').replaceAll('[', '\\[').replaceAll(']', '\\]');
  20. }
  21. export function invokedToolName(args: unknown): string | undefined {
  22. const record = readRecord(args);
  23. return (
  24. readNonEmptyString(record?.tool) ??
  25. readNonEmptyString(record?.tool_name) ??
  26. readNonEmptyString(record?.toolName)
  27. );
  28. }
  29. export function normalizeToolName(value: string): string {
  30. return value
  31. .trim()
  32. .toLowerCase()
  33. .replace(/[\s-]+/gu, '_');
  34. }
  35. export function parseMcpToolName(value: string): { server: string; tool: string } | undefined {
  36. const match = /^mcp__(.+?)__(.+)$/u.exec(value.trim());
  37. const server = match?.[1]?.trim();
  38. const tool = match?.[2]?.trim();
  39. return server && tool ? { server, tool } : undefined;
  40. }