Skip to main content
Glama
justfeltlikerunning

Sleeper Fantasy MCP

get_league_transactions

Retrieve league transactions such as trades, waivers, and free agent moves to track roster changes and manage your fantasy football team.

Instructions

Get league transactions including trades, waivers, and free agent moves

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
leagueNoLeague name (ROAD_TO_GLORY or DYNASTY), defaults to configured default
weekNoWeek number to get transactions for (defaults to current week)
transactionTypeNoFilter by transaction typeall
limitNoMaximum number of transactions to return (default: 20)
includeAllWeeksNoGet transactions from all weeks (default: false)

Implementation Reference

  • The main handler function `execute` that fetches league users, rosters, players, and transactions from Sleeper API, processes adds/drops/FAAB, formats them with player details and summaries, and returns structured JSON output.
    async execute(args: any) {
      const leagueConfig = getLeagueConfig(args.league);
      
      if (!leagueConfig) {
        throw new Error(`League configuration not found for: ${args.league}`);
      }
    
      const week = args.week || this.getCurrentWeek();
      const transactionType = args.transactionType || 'all';
      const limit = args.limit || 20;
      const includeAllWeeks = args.includeAllWeeks || false;
    
      try {
        // Fetch required data
        const fetchPromises = [
          fetch(`${config.api.baseUrl}/league/${leagueConfig.id}/users`),
          fetch(`${config.api.baseUrl}/league/${leagueConfig.id}/rosters`),
          fetch(`${config.api.baseUrl}/players/nfl`)
        ];
    
        // Add transactions for specific week or all weeks
        if (includeAllWeeks) {
          // Fetch transactions for weeks 1-18
          for (let w = 1; w <= 18; w++) {
            fetchPromises.push(
              fetch(`${config.api.baseUrl}/league/${leagueConfig.id}/transactions/${w}`)
                .catch(() => new Response('[]', { status: 404 })) // Handle weeks that don't exist yet
            );
          }
        } else {
          fetchPromises.push(
            fetch(`${config.api.baseUrl}/league/${leagueConfig.id}/transactions/${week}`)
          );
        }
    
        const responses = await Promise.all(fetchPromises);
        
        // Check core data responses
        if (!responses[0]?.ok || !responses[1]?.ok || !responses[2]?.ok) {
          throw new Error('Failed to fetch core league data');
        }
    
        const users = await responses[0].json();
        const rosters: SleeperRoster[] = await responses[1].json();
        const players = await responses[2].json();
    
        // Process transaction responses
        let allTransactions: any[] = [];
        
        if (includeAllWeeks) {
          // Process all week responses (starting from index 3)
          for (let i = 3; i < responses.length; i++) {
            if (responses[i]?.ok) {
              const weekTransactions = await (responses[i] as Response).json();
              if (Array.isArray(weekTransactions)) {
                allTransactions = allTransactions.concat(
                  weekTransactions.map(t => ({ ...t, week: i - 2 })) // Add week number
                );
              }
            }
          }
        } else {
          // Single week response
          if (responses[3]?.ok) {
            const weekTransactions = await responses[3].json();
            if (Array.isArray(weekTransactions)) {
              allTransactions = weekTransactions.map(t => ({ ...t, week }));
            }
          }
        }
    
        // Create lookup maps
        const userMap = new Map(users.map((user: any) => [user.user_id, user]));
        const rosterMap = new Map(rosters.map(roster => [roster.owner_id, roster]));
    
        // Filter and format transactions
        const formattedTransactions = allTransactions
          .filter(transaction => {
            if (transactionType === 'all') return true;
            return transaction.type === transactionType;
          })
          .map(transaction => {
            const creator = userMap.get(transaction.creator);
            const creatorRoster = rosterMap.get(transaction.creator);
    
            // Process adds and drops
            const adds = Object.entries(transaction.adds || {}).map(([playerId, rosterId]) => {
              const player = players[playerId];
              const targetRoster = rosters.find(r => r.roster_id === rosterId);
              const targetUser = targetRoster ? userMap.get(targetRoster.owner_id) : null;
              
              return {
                playerId,
                playerName: player ? `${player.first_name} ${player.last_name}` : 'Unknown Player',
                position: player?.position || 'UNK',
                team: player?.team || 'FA',
                acquiredBy: {
                  rosterId,
                  teamName: leagueConfig.teamName, // This would need roster metadata for team names
                  username: (targetUser as any)?.display_name || 'Unknown'
                }
              };
            });
    
            const drops = Object.entries(transaction.drops || {}).map(([playerId, rosterId]) => {
              const player = players[playerId];
              const sourceRoster = rosters.find(r => r.roster_id === rosterId);
              const sourceUser = sourceRoster ? userMap.get(sourceRoster.owner_id) : null;
              
              return {
                playerId,
                playerName: player ? `${player.first_name} ${player.last_name}` : 'Unknown Player',
                position: player?.position || 'UNK',
                team: player?.team || 'FA',
                droppedBy: {
                  rosterId,
                  teamName: leagueConfig.teamName, // This would need roster metadata for team names
                  username: (sourceUser as any)?.display_name || 'Unknown'
                }
              };
            });
    
            // Process FAAB budget
            const faabSpent = Object.entries(transaction.waiver_budget || {}).map(([rosterId, amount]) => {
              const roster = rosters.find(r => r.roster_id === parseInt(rosterId));
              const user = roster ? userMap.get(roster.owner_id) : null;
              
              return {
                rosterId: parseInt(rosterId),
                username: (user as any)?.display_name || 'Unknown',
                amount: Number(amount)
              };
            });
    
            return {
              transactionId: transaction.transaction_id,
              type: transaction.type,
              status: transaction.status,
              week: transaction.week,
              created: new Date(transaction.created).toISOString(),
              createdBy: {
                username: (creator as any)?.display_name || 'Unknown',
                rosterId: creatorRoster?.roster_id || null
              },
              adds: adds,
              drops: drops,
              faabSpent: faabSpent,
              totalFaabSpent: faabSpent.reduce((sum, f) => sum + f.amount, 0),
              rosterIds: transaction.roster_ids || [],
              metadata: {
                isWaiverClaim: transaction.type === 'waiver',
                isTrade: transaction.type === 'trade',
                isFreeAgent: transaction.type === 'free_agent',
                playerCount: (transaction.adds ? Object.keys(transaction.adds).length : 0) +
                            (transaction.drops ? Object.keys(transaction.drops).length : 0)
              }
            };
          })
          .sort((a, b) => new Date(b.created).getTime() - new Date(a.created).getTime())
          .slice(0, limit);
    
        const result = {
          league: args.league || config.defaultLeague,
          week: includeAllWeeks ? 'All weeks' : week,
          transactionType: transactionType,
          totalTransactions: formattedTransactions.length,
          timeRange: {
            includeAllWeeks: includeAllWeeks,
            requestedWeek: week
          },
          transactions: formattedTransactions,
          summary: {
            byType: this.getTransactionTypeSummary(formattedTransactions),
            totalFaabSpent: formattedTransactions.reduce((sum, t) => sum + t.totalFaabSpent, 0),
            mostActiveUsers: this.getMostActiveUsers(formattedTransactions),
            recentActivity: formattedTransactions.slice(0, 5).map(t => ({
              type: t.type,
              playerNames: [...t.adds.map(a => a.playerName), ...t.drops.map(d => d.playerName)],
              username: t.createdBy.username,
              timeAgo: this.getTimeAgo(t.created)
            }))
          }
        };
    
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(result, null, 2),
            },
          ],
        };
      } catch (error) {
        throw new Error(`Failed to get league transactions: ${error instanceof Error ? error.message : String(error)}`);
      }
    }
  • Input schema defining parameters: league (enum), week (1-18), transactionType (trade/waiver/free_agent/all), limit (1-100), includeAllWeeks (boolean).
    inputSchema = {
      type: "object",
      properties: {
        league: {
          type: "string",
          description: "League name (ROAD_TO_GLORY or DYNASTY), defaults to configured default",
          enum: ["ROAD_TO_GLORY", "DYNASTY"]
        },
        week: {
          type: "number",
          description: "Week number to get transactions for (defaults to current week)",
          minimum: 1,
          maximum: 18
        },
        transactionType: {
          type: "string",
          description: "Filter by transaction type",
          enum: ["trade", "waiver", "free_agent", "all"],
          default: "all"
        },
        limit: {
          type: "number",
          description: "Maximum number of transactions to return (default: 20)",
          minimum: 1,
          maximum: 100,
          default: 20
        },
        includeAllWeeks: {
          type: "boolean",
          description: "Get transactions from all weeks (default: false)",
          default: false
        }
      }
    };
  • src/index.ts:90-91 (registration)
    Registration in the main tool dispatcher switch statement, mapping tool name to TransactionsTool.execute call.
    case "get_league_transactions":
      return await transactionsTool.execute(args);
  • src/index.ts:33-33 (registration)
    Instantiation of the TransactionsTool class instance used for registration.
    const transactionsTool = new TransactionsTool();
  • src/index.ts:60-62 (registration)
    Inclusion of transactionsTool in the list of tools returned by ListToolsRequest handler.
      transactionsTool,
      stateScheduleTool,
    ],
Behavior2/5

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

With no annotations provided, the description carries full burden but only states what data is retrieved without disclosing behavioral traits. It doesn't mention whether this is a read-only operation, authentication requirements, rate limits, pagination behavior, or what happens with invalid parameters. The description is insufficient for a tool with 5 parameters and no annotation coverage.

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

Conciseness4/5

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

The description is a single, efficient sentence that gets straight to the point without unnecessary words. It's appropriately sized for a data retrieval tool, though it could be slightly more structured by front-loading the most critical information.

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

Completeness2/5

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

For a tool with 5 parameters, no annotations, and no output schema, the description is inadequate. It doesn't explain what format the transactions are returned in, how results are ordered, what happens when limits are exceeded, or provide examples of typical use cases. The description should do more to compensate for the lack of structured metadata.

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

Parameters3/5

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

The description doesn't add any parameter-specific information beyond what's already in the schema (which has 100% coverage). It mentions 'transactions' generally but doesn't explain how parameters like 'week', 'transactionType', or 'includeAllWeeks' affect the results. With complete schema coverage, the baseline score of 3 is appropriate.

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

Purpose4/5

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

The description clearly states the verb ('Get') and resource ('league transactions') with specific examples of what's included ('trades, waivers, and free agent moves'). It distinguishes from siblings like get_available_players or get_historical_scores by focusing on transaction data, but doesn't explicitly differentiate from all siblings.

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

Usage Guidelines2/5

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

No guidance is provided on when to use this tool versus alternatives. It doesn't mention prerequisites, timing considerations, or compare with sibling tools like get_historical_scores or get_league_info that might provide related data.

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/justfeltlikerunning/sleeper-fantasy-mcp'

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