Skip to main content
Glama
tomellen

SR P3 MCP Server

by tomellen

get_p3_current_playlist

Fetch the currently playing track on Sveriges Radio P3 with details on artist, title, album, and start/stop times.

Instructions

Fetch the currently playing song on Sveriges Radio P3 (channel 565). Returns the current song, previous song, and next song with details including artist, title, album, start/stop timestamps in UTC.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • src/server.ts:29-41 (registration)
    Tool registration in the TOOLS array with name 'get_p3_current_playlist', description, and input schema (empty object).
    const TOOLS: Tool[] = [
      {
        name: 'get_p3_current_playlist',
        description:
          'Fetch the currently playing song on Sveriges Radio P3 (channel 565). ' +
          'Returns the current song, previous song, and next song with details including ' +
          'artist, title, album, start/stop timestamps in UTC.',
        inputSchema: {
          type: 'object',
          properties: {},
          required: [],
        },
      },
  • Call handler in server.ts: validates input with GetCurrentPlaylistSchema, calls getCurrentPlaylist, and returns JSON response.
    case 'get_p3_current_playlist': {
      // Validate input (should be empty object)
      const validatedInput = GetCurrentPlaylistSchema.parse(args || {});
      const result = await getCurrentPlaylist(validatedInput);
    
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2),
          },
        ],
      };
    }
  • Zod schema (GetCurrentPlaylistSchema) defining empty input validation for the tool.
    export const GetCurrentPlaylistSchema = z.object({});
    
    export type GetCurrentPlaylistInput = z.infer<typeof GetCurrentPlaylistSchema>;
  • Main handler function getCurrentPlaylist: fetches playlist from SR API, finds P3 channel (ID 164), parses current/previous/next songs, and returns PlaylistResponse.
    export async function getCurrentPlaylist(
      _input: GetCurrentPlaylistInput
    ): Promise<PlaylistResponse> {
      const apiClient = getApiClient();
      const errors: string[] = [];
      const songs: Song[] = [];
    
      try {
        const response = await apiClient.getCurrentPlaylist();
    
        const currentTime = new Date().toISOString();
    
        // Find P3 channel in the response
        const p3Channel = response.channels?.find(ch => ch.id === P3_CHANNEL_ID);
        const playlist = p3Channel?.playlists?.playlist;
    
        if (!playlist) {
          throw new Error('No playlist data returned for P3 from Sveriges Radio API');
        }
    
        // Parse current song
        const currentSongs = normalizeToArray(playlist.song);
        const currentSong = currentSongs.length > 0 ? parseSong(currentSongs[0], currentTime) : null;
    
        // Parse previous song
        const previousSongs = normalizeToArray(playlist.previoussong);
        const previousSong = previousSongs.length > 0 ? parseSong(previousSongs[0], currentTime) : null;
    
        // Parse next song
        const nextSongs = normalizeToArray(playlist.nextsong);
        const nextSong = nextSongs.length > 0 ? parseSong(nextSongs[0], currentTime) : null;
    
        // Add songs in order: previous, current, next
        if (previousSong) songs.push(previousSong);
        if (currentSong) songs.push(currentSong);
        if (nextSong) songs.push(nextSong);
    
        if (songs.length === 0) {
          errors.push('No songs found in the current playlist');
        }
    
        return {
          songs,
          metadata: {
            channel: 'P3',
            channelId: P3_CHANNEL_ID,
            timestamp: currentTime,
            query: {
              type: 'current',
            },
          },
          errors: errors.length > 0 ? errors : undefined,
        };
      } catch (error) {
        // Convert error to user-friendly message
        const errorMessage =
          error instanceof Error
            ? error.message
            : 'An unexpected error occurred while fetching the current playlist';
    
        return {
          songs: [],
          metadata: {
            channel: 'P3',
            channelId: P3_CHANNEL_ID,
            timestamp: new Date().toISOString(),
            query: {
              type: 'current',
            },
          },
          errors: [errorMessage],
        };
      }
    }
  • Helper function parseSong: converts raw SR API song data to the Song interface with duration calculation.
    function parseSong(apiSong: SRApiSong | undefined, fallbackTime: string): Song | null {
      if (!apiSong) return null;
    
      const title = apiSong.title || 'Unknown Title';
      const artist = apiSong.artist || 'Unknown Artist';
      const startTime = apiSong.starttimeutc || fallbackTime;
      const stopTime = apiSong.stoptimeutc || fallbackTime;
    
      // Calculate duration in seconds
      let duration: number | undefined;
      try {
        const start = new Date(startTime).getTime();
        const stop = new Date(stopTime).getTime();
        if (!isNaN(start) && !isNaN(stop) && stop > start) {
          duration = Math.floor((stop - start) / 1000);
        }
      } catch {
        // Duration calculation failed, leave it undefined
      }
    
      return {
        title,
        artist,
        composer: apiSong.composer,
        albumName: apiSong.albumname,
        recordLabel: apiSong.recordlabel,
        startTimeUTC: startTime,
        stopTimeUTC: stopTime,
        duration,
        description: apiSong.description,
      };
    }
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description fully discloses return content (current, previous, next songs with details and UTC timestamps). It does not mention potential rate limits or authentication, but for a read-only fetch that is acceptable.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single sentence that conveys all necessary information without redundancy. Every part adds value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given zero parameters and no output schema, the description adequately explains what the tool returns (current, previous, next song with artist, title, album, timestamps). No missing context.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has no parameters, so the description does not need to add parameter meaning. Schema coverage is 100%, and baseline is 4 per instructions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description clearly states it fetches the currently playing song on Sveriges Radio P3, with specific channel number, and mentions details like artist, title, album, timestamps. This directly addresses the resource and action, and distinguishes from the sibling tool 'search_p3_playlist_by_date' which targets historical search.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for current playlist retrieval, and the sibling tool name suggests alternative for date-based search. While it doesn't explicitly state when not to use, the context is clear enough.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/tomellen/mcpsrtest'

If you have feedback or need assistance with the MCP directory API, please join our Discord server