Guide · Amazon Bedrock · Knowledge Base Retrieval

Amazon Bedrock Knowledge Base Data Sources for MCP Servers — Sync Jobs, Chunking Strategies, and Failed Document Handling

A Bedrock Knowledge Base is only as fresh as its last ingestion job — and failed documents do not fail the job, so your knowledge base can silently contain stale or incomplete data. Understanding how ingestion works is critical for MCP servers that surface knowledge base content: a retrieval tool that returns outdated answers because a sync job silently skipped 40 documents is harder to debug than a tool that throws an explicit error. Bedrock supports five data source types (S3, web crawler, Confluence, Salesforce, SharePoint), three chunking strategies with meaningfully different retrieval tradeoffs, and an async ingestion API (StartIngestionJobCommand + GetIngestionJobCommand) that you must poll to completion. The two most common operational failures are not monitoring failed document counts (the job reports COMPLETE with failures buried in statistics) and choosing FIXED_SIZE chunking for structured documentation (which splits mid-sentence and loses context, hurting retrieval quality). This guide covers data source configuration for S3 and web crawler, all three chunking strategies with tradeoff tables, the ingestion polling pattern, and how to expose ingestion management as MCP tools. For retrieval search modes, see Hybrid Search. For metadata attribute filters, see Metadata Filtering. For RAG in a single call, see RetrieveAndGenerate.

TL;DR

Use SEMANTIC chunking for prose documentation (better sentence boundaries = better retrieval). Use HIERARCHICAL for long documents where top-level context must accompany fine-grained chunks. Use FIXED_SIZE only for structured data or when chunk size must be tightly controlled. After StartIngestionJobCommand, poll GetIngestionJobCommand until status is COMPLETE or FAILED — a COMPLETE job can still have failed documents; check statistics.numberOfDocumentsFailed.

Data source types

TypeSourceAuthNotes
S3S3 bucket (PDF, DOCX, TXT, HTML, MD, CSV, XLSX)IAM role on KBMost flexible; supports .metadata.json companion files
Web crawlerSeed URLs; follows links up to configured depthNone (public) or basic authRespects robots.txt by default; JS-rendered pages not supported
ConfluenceConfluence Cloud spaceOAuth 2.0 or API token via Secrets ManagerCrawls pages and attachments; spaces configured by space key
SalesforceSalesforce org objects (Knowledge Articles, Cases, etc.)OAuth 2.0 via Secrets ManagerField-level sync; requires specific Salesforce edition
SharePointSharePoint Online site(s)OAuth 2.0 via Secrets ManagerCrawls document libraries; requires Microsoft app registration

For MCP servers, S3 is the most common data source because it integrates easily with existing document pipelines (CI builds, Lambda processors, manual uploads) and supports the metadata filtering workflow via .metadata.json companion files. Web crawler is useful for indexing public documentation sites without an S3 upload step.

S3 data source configuration

import {
  BedrockAgentClient,
  CreateDataSourceCommand,
  type CreateDataSourceCommandInput,
} from "@aws-sdk/client-bedrock-agent";

const client = new BedrockAgentClient({ region: "us-east-1" });

const input: CreateDataSourceCommandInput = {
  knowledgeBaseId: "KB_ID",
  name: "platform-docs-s3",
  dataSourceConfiguration: {
    type: "S3",
    s3Configuration: {
      bucketArn: "arn:aws:s3:::my-docs-bucket",
      inclusionPrefixes: ["docs/", "runbooks/"],
      // exclusionPrefixes: ["docs/archive/"], // optional
    },
  },
  vectorIngestionConfiguration: {
    chunkingConfiguration: {
      chunkingStrategy: "SEMANTIC",
      semanticChunkingConfiguration: {
        maxTokens: 300,
        bufferSize: 1,
        breakpointPercentileThreshold: 95,
      },
    },
  },
};

Web crawler data source configuration

const webCrawlerInput: CreateDataSourceCommandInput = {
  knowledgeBaseId: "KB_ID",
  name: "docs-site-crawler",
  dataSourceConfiguration: {
    type: "WEB",
    webConfiguration: {
      sourceConfiguration: {
        urlConfiguration: {
          seedUrls: [
            { url: "https://docs.myproduct.com/" },
            { url: "https://docs.myproduct.com/api-reference/" },
          ],
        },
      },
      crawlerConfiguration: {
        crawlerLimits: {
          rateLimit: 50, // max pages per minute
        },
        exclusionFilters: [".*\\.pdf$", ".*changelog.*"],
        inclusionFilters: ["https://docs.myproduct.com/.*"],
        scope: "HOST_ONLY", // or "SUBDOMAINS" to follow to sub-domains
      },
    },
  },
  vectorIngestionConfiguration: {
    chunkingConfiguration: {
      chunkingStrategy: "SEMANTIC",
      semanticChunkingConfiguration: {
        maxTokens: 300,
        bufferSize: 1,
        breakpointPercentileThreshold: 95,
      },
    },
  },
};

The web crawler does not render JavaScript — it fetches raw HTML. Single-page apps (React/Vue docs sites that render client-side) will produce empty chunks. For JS-rendered documentation, export a static build to S3 and use the S3 data source instead.

Chunking strategies

StrategyHow it worksBest forKey parameter
SEMANTICGroups sentences into chunks at semantic breakpoints detected by an embedding model; respects natural topic shiftsProse documentation, blog posts, runbooks, KB articlesmaxTokens (300–500), breakpointPercentileThreshold (90–97)
HIERARCHICALCreates parent chunks (larger context) and child chunks (fine-grained); child chunks carry parent content during retrievalLong technical documents where section context is needed alongside detailParent maxTokens (1500–2000), child maxTokens (300–500), overlap tokens
FIXED_SIZESplits at a fixed token count with optional overlapStructured data, CSVs, tables, source code where semantic boundaries don't applymaxTokens (200–400), overlapPercentage (10–20%)
NONETreats each document as one chunk; no splittingVery short documents (FAQ entries, single-topic pages)None

SEMANTIC chunking — the recommended default

SEMANTIC chunking uses an embedding model to detect where topic transitions occur within a document. It groups consecutive sentences together as long as the semantic similarity stays above a threshold, then starts a new chunk when the similarity drops below the breakpointPercentileThreshold. The result is chunks that correspond to coherent topics rather than arbitrary token counts.

chunkingConfiguration: {
  chunkingStrategy: "SEMANTIC",
  semanticChunkingConfiguration: {
    maxTokens: 300,          // hard upper limit per chunk
    bufferSize: 1,           // sentences of context window for similarity detection (1–3)
    breakpointPercentileThreshold: 95,  // higher = fewer, larger chunks (80–99)
  },
},

Increasing breakpointPercentileThreshold produces fewer, larger chunks (fewer breakpoints triggered). Decreasing it produces more granular chunks. For technical documentation, 95 is a good starting point — lower values fragment headings from their body text.

HIERARCHICAL chunking — for long documents with section context

HIERARCHICAL chunking addresses a common retrieval failure: a fine-grained chunk about "token limits" is retrieved, but without the surrounding section heading it is unclear which model or service the limits apply to. Hierarchical mode creates parent chunks at section-level granularity and child chunks at paragraph-level granularity. At retrieval time, Bedrock returns the child chunk content (smaller, more precise) but includes the parent chunk text as surrounding context in the retrieved reference:

chunkingConfiguration: {
  chunkingStrategy: "HIERARCHICAL",
  hierarchicalChunkingConfiguration: {
    levelConfigurations: [
      { maxTokens: 1500 }, // parent chunk size
      { maxTokens: 300 },  // child chunk size
    ],
    overlapTokens: 60,     // token overlap between consecutive child chunks
  },
},

HIERARCHICAL chunking increases storage requirements (parent and child embeddings are stored separately) and ingestion time. Use it for documents longer than 2,000 words where section-level context is critical for correct interpretation of retrieved passages.

Starting and monitoring ingestion jobs

Ingestion is an asynchronous operation. StartIngestionJobCommand returns a job ID and status STARTING; you must poll GetIngestionJobCommand until the job reaches a terminal state:

import {
  BedrockAgentClient,
  StartIngestionJobCommand,
  GetIngestionJobCommand,
} from "@aws-sdk/client-bedrock-agent";

const bedrockAgent = new BedrockAgentClient({ region: "us-east-1" });

export async function syncAndWait(
  knowledgeBaseId: string,
  dataSourceId: string,
  pollIntervalMs = 5000,
  timeoutMs = 300_000,
): Promise<{ status: string; stats: Record<string, number> }> {
  const startResp = await bedrockAgent.send(
    new StartIngestionJobCommand({ knowledgeBaseId, dataSourceId }),
  );
  const ingestionJobId = startResp.ingestionJob?.ingestionJobId;
  if (!ingestionJobId) throw new Error("No ingestionJobId returned");

  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    await new Promise((r) => setTimeout(r, pollIntervalMs));

    const getResp = await bedrockAgent.send(
      new GetIngestionJobCommand({ knowledgeBaseId, dataSourceId, ingestionJobId }),
    );
    const job = getResp.ingestionJob!;

    if (job.status === "COMPLETE" || job.status === "FAILED" || job.status === "STOPPED") {
      const stats = job.statistics ?? {};
      const failedCount = stats.numberOfDocumentsFailed ?? 0;

      if (job.status === "FAILED") {
        throw new Error(`Ingestion job FAILED: ${JSON.stringify(job.failureReasons)}`);
      }
      if (failedCount > 0) {
        // Job "COMPLETE" but some documents failed — log, do not throw
        console.warn(
          `Ingestion COMPLETE with ${failedCount} failed document(s). ` +
          `Scanned: ${stats.numberOfDocumentsScanned}, ` +
          `Indexed: ${stats.numberOfNewDocumentsIndexed}, ` +
          `Deleted: ${stats.numberOfDocumentsDeleted}`,
        );
      }

      return {
        status: job.status,
        stats: {
          scanned: stats.numberOfDocumentsScanned ?? 0,
          indexed: stats.numberOfNewDocumentsIndexed ?? 0,
          deleted: stats.numberOfDocumentsDeleted ?? 0,
          failed: failedCount,
          modified: stats.numberOfModifiedDocumentsIndexed ?? 0,
        },
      };
    }
    // Status is STARTING or IN_PROGRESS — continue polling
  }
  throw new Error(`Ingestion job timed out after ${timeoutMs}ms`);
}

Job status values

StatusMeaningTerminal?
STARTINGJob queued, not yet processingNo
IN_PROGRESSActively processing documentsNo
COMPLETEJob finished; some documents may still have failedYes
FAILEDJob-level failure (data source unreachable, IAM error, quota exceeded)Yes
STOPPINGStop requested, not yet stoppedNo
STOPPEDJob was manually stoppedYes

Gotcha: COMPLETE does not mean all documents indexed

The most operationally dangerous behavior of the ingestion API: a job reports COMPLETE even if individual documents failed to ingest. The failures are recorded in statistics.numberOfDocumentsFailed and in the per-document failure reasons available via the job details, but the top-level status is still COMPLETE. If you do not check numberOfDocumentsFailed, you will deploy what you believe is a fully-synced knowledge base that is silently missing documents. Set up a CloudWatch alarm or write a check in your deployment pipeline that fails the deploy if numberOfDocumentsFailed > 0.

Exposing ingestion management as MCP tools

For teams that run knowledge base syncs on a schedule or trigger them on document uploads, exposing sync status as an MCP tool lets AI agents check whether the knowledge base is fresh before issuing retrieval queries:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

const server = new McpServer({ name: "kb-manager", version: "1.0.0" });

server.tool(
  "trigger_kb_sync",
  {
    knowledge_base_id: z.string(),
    data_source_id: z.string(),
  },
  async ({ knowledge_base_id, data_source_id }) => {
    const result = await syncAndWait(knowledge_base_id, data_source_id);
    const summary =
      `Sync ${result.status}. ` +
      `Indexed: ${result.stats.indexed}, ` +
      `Modified: ${result.stats.modified}, ` +
      `Deleted: ${result.stats.deleted}, ` +
      `Failed: ${result.stats.failed}`;
    return { content: [{ type: "text", text: summary }] };
  },
);

server.tool(
  "get_kb_sync_status",
  {
    knowledge_base_id: z.string(),
    data_source_id: z.string(),
    ingestion_job_id: z.string(),
  },
  async ({ knowledge_base_id, data_source_id, ingestion_job_id }) => {
    const resp = await bedrockAgent.send(
      new GetIngestionJobCommand({
        knowledgeBaseId: knowledge_base_id,
        dataSourceId: data_source_id,
        ingestionJobId: ingestion_job_id,
      }),
    );
    const job = resp.ingestionJob!;
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify({
            status: job.status,
            statistics: job.statistics,
            failureReasons: job.failureReasons,
          }, null, 2),
        },
      ],
    };
  },
);

Monitoring knowledge base freshness with AliveMCP

AliveMCP monitors MCP server tool call health, which includes the trigger_kb_sync and get_kb_sync_status tools when exposed by your MCP server. Time-to-sync latency, job failure rates, and failed document counts are all visible in the AliveMCP dashboard. Setting up a synthetic monitor that calls trigger_kb_sync on a schedule — and alerts if numberOfDocumentsFailed > 0 — closes the gap between silent ingestion failures and production-impacting retrieval degradation.

Related pages in this arc

For the foundational overview, see Bedrock Knowledge Base for MCP Servers. For Bedrock guardrails, see Bedrock Guardrails for MCP Servers.