Skip to main content
Glama
ibm-ecm

IBM Core Content Services MCP Server

Official
by ibm-ecm

checkin_document

Check in a document to a content repository by specifying its identifier and optionally providing updated properties, file content, or check-in parameters.

Instructions

Checks in a document in the content repository with specified properties.

:param identifier: The identifier (required). This can be either a reservation_id or document_id. Reservation ID (GUID) is prioritized. Otherwise, we use document_id (GUID). :param checkin_action: Check-in action parameters for the document. :param document_properties: Properties to update for the document during check-in. :param file_paths: Optional list of file paths to upload as the document's content.

:returns: If successful, returns a Document object with its updated properties. If unsuccessful, returns a ToolError with details about the failure.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
identifierYes
checkin_actionNo
document_propertiesNo
file_pathsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main handler function for the 'checkin_document' tool. It executes a checkinDocument GraphQL mutation, processes optional file uploads via file_paths and document properties, and returns a Document instance or ToolError.
    @mcp.tool(
        name="checkin_document",
    )
    async def checkin_document(
        identifier: str,
        checkin_action: Optional[SubCheckinActionInput] = SubCheckinActionInput(),
        document_properties: Optional[DocumentPropertiesInput] = None,
        file_paths: Optional[List[str]] = None,
    ) -> Union[Document, ToolError]:
        """
        Checks in a document in the content repository with specified properties.
    
        :param identifier: The identifier (required). This can be either a reservation_id or document_id.
                          Reservation ID (GUID) is prioritized.
                          Otherwise, we use document_id (GUID).
        :param checkin_action: Check-in action parameters for the document.
        :param document_properties: Properties to update for the document during check-in.
        :param file_paths: Optional list of file paths to upload as the document's content.
    
        :returns: If successful, returns a Document object with its updated properties.
                 If unsuccessful, returns a ToolError with details about the failure.
        """
        method_name = "checkin_document"
        try:
            # Prepare the mutation
            mutation = """
            mutation ($object_store_name: String!, $identifier: String!,
                     $document_properties: DocumentPropertiesInput, $checkin_action: SubCheckinActionInput!) {
              checkinDocument(
                repositoryIdentifier: $object_store_name
                identifier: $identifier
                documentProperties: $document_properties
                checkinAction: $checkin_action
              ) {
                id
                className
                reservation{
                    isReserved
                    id
                }
                currentVersion{
                    contentElements{
                        ... on ContentTransferType {
                            retrievalName
                            contentType
                            contentSize
                            downloadUrl
                        }
                    }
                }
                properties {
                  id
                  value
                }
              }
            }
            """
    
            # Prepare variables for the GraphQL query
            variables = {
                "object_store_name": graphql_client.object_store,
                "identifier": identifier,
                "document_properties": None,
                "checkin_action": None,
            }
    
            # Process file paths
            file_paths_dict = {}
    
            # Handle file upload if file paths are provided
            if file_paths:
                try:
                    # Initialize document_properties if not provided
                    if not document_properties:
                        document_properties = DocumentPropertiesInput()
    
                    file_paths_dict = document_properties.process_file_content(
                        file_paths
                    )
                except Exception as e:
                    logger.error("%s failed: %s", method_name, str(e))
                    logger.error(traceback.format_exc())
                    return ToolError(
                        message=f"{method_name} failed: {str(e)}. Trace available in server logs."
                    )
    
            # Process document properties if provided
            if document_properties:
                try:
                    document_properties.eval()
                    transformed_props = document_properties.transform_properties_dict(
                        exclude_none=True
                    )
                    variables["document_properties"] = transformed_props
                except Exception as e:
                    logger.error("Error transforming document properties: %s", str(e))
                    logger.error(traceback.format_exc())
                    return ToolError(
                        message=f"{method_name} failed: {str(e)}. Trace available in server logs."
                    )
    
            if checkin_action:
                # Handle checkin action if provided                # Use model_dump with exclude_none for cleaner code
                variables["checkin_action"] = checkin_action.model_dump(
                    exclude_none=True
                )
    
            # Execute the GraphQL mutation
            if file_paths_dict:
                # Use execute with file_paths for file upload
                logger.info("Executing document check-in with file upload")
                response = graphql_client.execute(
                    query=mutation,
                    variables=variables,
                    file_paths=file_paths_dict,
                )
            else:
                # Use execute_async for regular document check-in
                logger.info("Executing document check-in")
                response = await graphql_client.execute_async(
                    query=mutation, variables=variables
                )
    
            # Handle errors
            if "errors" in response:
                logger.error("GraphQL error: %s", response["errors"])
                return ToolError(message=f"{method_name} failed: {response['errors']}")
    
            # Create and return a Document instance from the response
            return Document.create_an_instance(
                graphQL_changed_object_dict=response["data"]["checkinDocument"],
                class_identifier=DEFAULT_DOCUMENT_CLASS,
            )
    
        except Exception as e:
            logger.error("%s failed: %s", method_name, str(e))
            logger.error(traceback.format_exc())
            return ToolError(
                message=f"{method_name} failed: {str(e)}. Trace available in server logs."
            )
  • Registration of the 'checkin_document' tool via the FastMCP @mcp.tool decorator. This is inside the register_document_tools function.
    @mcp.tool(
        name="checkin_document",
    )
  • Schema/input type definition for SubCheckinActionInput used by the checkin_document tool. Defines autoClassify and checkinMinorVersion fields.
    class SubCheckinActionInput(BaseModel):
        """Input for document check-in action."""
    
        autoClassify: Optional[bool] = Field(
            default=None,
            description="Whether to automatically classify the document. User must explicitly set this value, else it will be None by default",
        )
        checkinMinorVersion: Optional[bool] = Field(
            default=False,
            description="Whether to check in as a minor version. By default, this is False since we always check in as major version unless specified by the user.",
        )
  • Helper method on DocumentPropertiesInput (inherited from CustomInputBase) that processes file paths into content elements for file upload during checkin_document.
    def process_file_content(
        self,
        file_paths_list: List[str],
    ) -> Dict[str, str]:
        """
        Process file content and prepare document properties and file paths dictionary.
        This method is used by document operations that handle file uploads.
    
        Args:
            file_paths_list: List of file paths to process
    
        Returns:
            Dictionary mapping variable names to file paths
    
        Raises:
            ValueError: If a file path doesn't exist or is invalid
        """
        logger = logging.getLogger(__name__)
    
        # Create ContentElementListInput with replace action
        content_elements = ContentElementListInput()
        content_elements.replace = []
    
        # Set up file_paths dictionary for the execute method
        file_paths_dict = {}
    
        # Check if file_paths_list is empty
        if not file_paths_list:
            raise ValueError("No file paths provided")
    
        # Filter out non-existent files and collect invalid files
        invalid_files = []
        valid_file_paths = []
        for path in file_paths_list:
            if not path:
                invalid_files.append(f"Empty file path")
                continue
            if not os.path.exists(path):
                invalid_files.append(f"File not found: {path}")
                continue
            if not os.path.isfile(path):
                invalid_files.append(f"Not a file: {path}")
                continue
            valid_file_paths.append(path)
    
        # Raise error if any invalid files were found
        if invalid_files:
            error_message = "Invalid file(s): " + "; ".join(invalid_files)
            logger.error(error_message)
            raise ValueError(error_message)
    
        # Raise error if no valid files remain
        if not valid_file_paths:
            error_message = "No valid files to process"
            logger.error(error_message)
            raise ValueError(error_message)
    
        # Process each file path
        for i, path in enumerate(valid_file_paths):
            # Create a variable name for each file upload
            file_var_name = "contvar" if i == 0 else f"contvar{i+1}"
    
            # Get mime type for content type
            mime_type = mimetypes.guess_type(path)[0] or "application/octet-stream"
            file_name = os.path.basename(path)
    
            # Create SubContentTransferInput for this file
            content_transfer = SubContentTransferInput(
                content=file_var_name, retrievalName=file_name
            )
    
            # Create BaseContentElementInput with ContentTransfer
            content_element = BaseContentElementInput(
                type=ContentElementType.CONTENT_TRANSFER,
                contentType=mime_type,
                subContentTransfer=content_transfer,
                insertAction=InsertDependentActionInput(
                    newIndex=i
                ),  # Use index i instead of hardcoded 0
            )
    
            # Add to the replace list
            content_elements.replace.append(content_element)
    
            # Add to file_paths dictionary
            file_paths_dict[file_var_name] = path
    
        # Add content elements to document properties
        try:
            self.add_content_elements(content_elements)
        except Exception as e:
            logger.error("Error adding content elements: %s", str(e))
            logger.error(traceback.format_exc())
    
        return file_paths_dict
  • Schema for DocumentPropertiesInput used as parameter in checkin_document tool for specifying document properties during check-in.
    class DocumentPropertiesInput(CustomInputBase):
        """Input for document properties."""
    
        properties: Optional[List[PropertyIdentifierAndScalarValue]] = Field(
            default=None, description="Properties for Document"
        )
        name: Optional[str] = Field(
            default=None,
            description="Name sets DocumentTitle or whatever property is configured as the Name property",
        )
        owner: Optional[str] = Field(default=None, description="Owner")
        content: Optional[str] = Field(
            default=None,
            description="Content can be specified if this represents a Reservation document or document creation",
        )
        mimeType: Optional[str] = Field(default=None, description="Mime type")
        compoundDocumentState: Optional[str] = Field(
            default=None, description="Compound document state"
        )
        cmRetentionDate: Optional[datetime] = Field(
            default=None, description="Retention date"
        )
        # contentElements field removed from the model to prevent agents from interpreting and creating this field
        # Instead, we use the methods from CustomInputBase to add content elements programmatically
    
        # Commented out references to ObjectReferenceInput, PermissionListInput, ObjectPropertyInput
        """
        objectProperties: Optional[List[ObjectPropertyInput]] = Field(
            default=None, description="Object properties"
        )
        replicationGroup: Optional[ObjectReferenceInput] = Field(
            default=None, description="Replication group"
        )
        permissions: Optional[PermissionListInput] = Field(
            default=None, description="Permissions"
        )
        securityPolicy: Optional[ObjectReferenceInput] = Field(
            default=None, description="Security policy"
        )
        securityFolder: Optional[ObjectReferenceInput] = Field(
            default=None, description="Security folder"
        )
        storagePolicy: Optional[ObjectReferenceInput] = Field(
            default=None, description="Storage policy"
        )
        documentLifecyclePolicy: Optional[ObjectReferenceInput] = Field(
            default=None, description="Document lifecycle policy"
        )
        storageArea: Optional[ObjectReferenceInput] = Field(
            default=None, description="Storage area"
        )
        """
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It discloses that check-in updates properties and can upload content via file_paths, and returns a Document object or ToolError. However, it does not specify side effects like version creation or behavior when the document is already checked in.

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

Conciseness3/5

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

The description is front-loaded with the main purpose but then includes a lengthy parameter list that largely duplicates schema descriptions. It could be more concise by omitting redundant parameter details.

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

Completeness4/5

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

Given that an output schema exists and the tool has 4 parameters with nested objects, the description covers the main action, parameter types, and return format. It lacks usage context but is otherwise complete for the check-in operation.

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 adds meaningful clarification for the identifier parameter (reservation_id vs document_id priority) and file_paths (upload as content). However, the input schema already contains detailed descriptions for most sub-fields, so the description's additional value is modest.

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?

The description clearly states it 'Checks in a document', using a specific verb and resource. It distinguishes itself from sibling tools like checkout_document and cancel_document_checkout by the action of checking in.

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?

The description does not provide explicit guidance on when to use this tool versus alternatives. It includes parameter details but no context about prerequisites (e.g., document must be checked out) or situations to avoid.

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/ibm-ecm/ibm-content-services-mcp-server'

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