Skip to main content
Glama

construct_context_pack

Destructive

Create bounded context packs from contextfs by specifying queries, item limits, character constraints, and namespaces for structured information retrieval.

Instructions

Construct a bounded context pack from contextfs

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryNo
maxItemsNo
maxCharsNo
namespacesNo

Implementation Reference

  • The core implementation of `constructContextPack` which constructs a context pack by querying, ranking, and structuring documents from the context filesystem.
    function constructContextPack({ query = '', maxItems = 8, maxChars = 6000, namespaces = [] } = {}) {
      const normalizedNamespaces = normalizeNamespaces(namespaces);
      const tokens = tokenizeQuery(query);
      const sourceHash = getSourceHash(normalizedNamespaces);
    
      const cacheHit = findSemanticCacheHit({
        query,
        namespaces: normalizedNamespaces,
        maxItems,
        maxChars,
      });
    
      if (cacheHit) {
        const packId = `pack_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
        const cachedPack = cacheHit.entry.pack;
        const pack = {
          ...cachedPack,
          packId,
          query,
          createdAt: nowIso(),
          cache: {
            hit: true,
            similarity: Number(cacheHit.score.toFixed(4)),
            matchedQuery: cacheHit.entry.query,
            sourcePackId: cachedPack.packId,
          },
        };
    
        appendJsonl(path.join(CONTEXTFS_ROOT, NAMESPACES.provenance, 'packs.jsonl'), pack);
        recordProvenance({
          type: 'context_pack_cache_hit',
          packId,
          sourcePackId: cachedPack.packId,
          query,
          similarity: Number(cacheHit.score.toFixed(4)),
          itemCount: Array.isArray(pack.items) ? pack.items.length : 0,
        });
    
        return pack;
      }
    
      const candidates = loadCandidates(normalizedNamespaces)
        .map((doc) => ({ doc, score: scoreDocument(doc, tokens) }))
        .sort((a, b) => b.score - a.score);
    
      const selected = [];
      let usedChars = 0;
      let skippedByMaxChars = 0;
    
      for (const item of candidates) {
        if (selected.length >= maxItems) break;
    
        const snippet = `${item.doc.title}\n${item.doc.content || ''}`;
        if (usedChars + snippet.length > maxChars) {
          skippedByMaxChars += 1;
          continue;
        }
    
        // Context Structuralizer (EvoSkill Hardening)
        // Parse unstructured text back into a high-density State Document
        const structuredContext = {
          rawContent: item.doc.content || '',
          reasoning: null,
          whatWentWrong: null,
          whatToChange: null,
          rubricFailure: null
        };
    
        const lines = (item.doc.content || '').split('\n');
        for (const line of lines) {
          if (line.startsWith('Reasoning:')) structuredContext.reasoning = line.replace('Reasoning:', '').trim();
          else if (line.startsWith('What went wrong:')) structuredContext.whatWentWrong = line.replace('What went wrong:', '').trim();
          else if (line.startsWith('How to avoid:')) structuredContext.whatToChange = line.replace('How to avoid:', '').trim();
          else if (line.startsWith('Rubric failing criteria:')) structuredContext.rubricFailure = line.replace('Rubric failing criteria:', '').trim();
        }
    
        selected.push({
          id: item.doc.id,
          namespace: item.doc.namespace,
          title: item.doc.title,
          structuredContext,
          tags: item.doc.tags || [],
          score: item.score,
        });
        usedChars += snippet.length;
      }
    
      const visibility = {
        itemCount: selected.length,
        sourceCandidateCount: candidates.length,
        hiddenCount: Math.max(candidates.length - selected.length, 0),
        maxItemsHit: candidates.length > maxItems && selected.length >= maxItems,
        maxCharsHit: skippedByMaxChars > 0,
        skippedByMaxChars,
        remainingCharBudget: Math.max(maxChars - usedChars, 0),
        visibleTitles: selected.slice(0, 5).map((item) => item.title),
      };
    
      const packId = `pack_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
      const pack = {
        packId,
        query,
        maxItems,
        maxChars,
        usedChars,
        namespaces: normalizedNamespaces,
        createdAt: nowIso(),
        items: selected,
        visibility,
        cache: {
          hit: false,
        },
        sourceHash,
      };
    
      appendJsonl(path.join(CONTEXTFS_ROOT, NAMESPACES.provenance, 'packs.jsonl'), pack);
      appendSemanticCacheEntry({
        id: `cache_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
        timestamp: nowIso(),
        key: buildSemanticCacheKey({
          namespaces: normalizedNamespaces,
          maxItems,
          maxChars,
        }),
        query,
        tokens,
        sourceHash,
        pack,
      });
      recordProvenance({
        type: 'context_pack_constructed',
        packId,
        query,
        itemCount: selected.length,
        usedChars,
        sourceHash,
      });
    
      return pack;
    }
Behavior3/5

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

The annotation 'destructiveHint: true' indicates potential destructive behavior, which the description does not contradict. However, the description adds no behavioral context beyond this—it does not explain what 'destructive' entails (e.g., data modification, resource consumption), nor does it cover other traits like rate limits, authentication needs, or side effects. With annotations present, the bar is lower, but the description provides minimal additional value.

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, efficient sentence with no wasted words. It is appropriately sized and front-loaded, though this brevity contributes to its lack of detail. Every word serves a purpose, even if insufficient.

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?

Given the tool's complexity (4 parameters, destructive hint, no output schema), the description is incomplete. It lacks parameter explanations, usage context, behavioral details, and output information. The annotations provide some safety cues, but the description does not adequately address the gaps for a tool with multiple inputs and potential destructive effects.

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

Parameters2/5

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

Schema description coverage is 0%, so parameters are undocumented in the schema. The description does not mention any parameters or their semantics, failing to compensate for the schema gap. It does not explain what 'query', 'maxItems', 'maxChars', or 'namespaces' mean or how they affect the construction process.

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

Purpose2/5

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

The description 'Construct a bounded context pack from contextfs' restates the tool name with minimal elaboration. It mentions a verb ('construct') and resource ('bounded context pack'), but is vague about what a 'bounded context pack' or 'contextfs' are, and does not differentiate from siblings like 'evaluate_context_pack' or 'context_provenance'. This is borderline tautological with the name.

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

Usage Guidelines1/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 does not mention prerequisites, conditions for use, or contrast with sibling tools such as 'evaluate_context_pack' or 'recall'. The description lacks any contextual cues for tool selection.

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/IgorGanapolsky/mcp-memory-gateway'

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